我正在嘗試創建一個輸出大量資料的頁面,并根據視窗大小動態換行文本。我從設定開始wraplength = self.master.winfo_width(),它將文本換行設定為當前視窗大小,但當視窗改變時它不會改變。我找到了這個答案,它似乎可以解決問題,但是當我自己嘗試重新創建它時,出了點問題。我懷疑我對.bind或有誤解<Configure>,但我不能確定。我的基本代碼如下:
from tkinter import *
class Wrap_example(Frame):
def __init__(self):
Frame.__init__(self)
self.place(relx=0.5, anchor='n')
#Initalize list and variable that populates it
self.data_list = []
self.data = 0
#Button and function for creating a bunch of numbers to fill the space
self.button = Button(self, text = "Go", command = self.go)
self.button.grid()
def go(self):
for self.data in range(1, 20000, 100):
self.data_list.append(self.data)
#Label that holds the data, text = list, wraplength = current window width
self.data = Label(self, text = self.data_list, wraplength = self.master.winfo_width(), font = 'arial 30')
self.data.grid()
#Ostensibly sets the label to dynamically change wraplength to match new window size when window size changes
self.data.bind('<Configure>', self.rewrap())
def rewrap(self):
self.data.config(wraplength = self.master.winfo_width())
frame01 = Wrap_example()
frame01.mainloop()
一些注意事項:我嘗試lambda直接使用鏈接答案中所示的 ,但它沒有用。如果我洗掉 rewrap 函式并使用self.data.bind('<Configure>', lambda e: self.data.config(wraplength=self.winfo_width()),它會拋出一個通用的語法錯誤,總是針對該行之后的第一個字符(如果函式保留在 def 中,則在 frame01 中的 f 被注釋掉)。保持重新包裝原樣不會引發錯誤,但它也不會執行任何其他明顯的功能。單擊“Go”將始終生成以當前視窗大小換行的資料,并且永遠不會更改。
uj5u.com熱心網友回復:
有幾個問題:
Wrap_example調整視窗大小時,框架不會填滿所有水平空間- 調整框架大小時,標簽
self.data不會填充框架內的所有水平空間Wrap_example self.rewrap()將在執行該行時立即執行self.data.bind('<Configure>', self.rewrap())
要解決上述問題:
- 設定
relwidth=1在self.place(...) - 稱呼
self.columnconfigure(0, weight=1) - 使用
self.data.bind('<Configure>', self.rewrap)(沒有 () afterrewrap) 并添加event引數rewrap()
from tkinter import *
class Wrap_example(Frame):
def __init__(self):
Frame.__init__(self)
self.place(relx=0.5, anchor='n', relwidth=1) ### add relwidth=1
self.columnconfigure(0, weight=1) ### make column 0 use all available horizontal space
#Initalize list and variable that populates it
self.data_list = []
self.data = 0
#Button and function for creating a bunch of numbers to fill the space
self.button = Button(self, text = "Go", command = self.go)
self.button.grid()
def go(self):
for self.data in range(1, 20000, 100):
self.data_list.append(self.data)
#Label that holds the data, text = list, wraplength = current window width
self.data = Label(self, text = self.data_list, wraplength = self.master.winfo_width(), font = 'arial 30')
self.data.grid()
#Ostensibly sets the label to dynamically change wraplength to match new window size when window size changes
self.data.bind('<Configure>', self.rewrap) ### remove () after rewrap
def rewrap(self, event): ### add event argument
self.data.config(wraplength = self.master.winfo_width())
frame01 = Wrap_example()
frame01.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398961.html
上一篇:帶按鈕的if陳述句
