代碼:
from tkinter import *
#screen 1
scr1 = Tk()
scr1.configure(bg='#2e3033')
canvas = []
teamCommentsButton = []
#update Vissuals
def updateTeams():
for x in range(6):
onClick = lambda : comments(x 10)
canvas[x].itemconfig(teamCommentsButton[x], command = onClick)
def comments (team):
print(team)
comments = Toplevel(scr1)
for x in range(6):
canvas.append(Canvas(scr1, width = 840, height = 326, bg='#2e3033', highlightthickness=1, highlightbackground='#2e3033'))
teamCommentsButton.append(Button(canvas[x], text='?', command = lambda : comments(x), width = 2, height = 1))
teamCommentsButton[x].place(x = 20, y = 20)
canvas[x].grid(column = 0 if x < 3 else 1, row = (x if x < 3 else x - 3))
scr1.title('Pit TV - Match')
updateTeams()
scr1.mainloop()
錯誤:
Traceback (most recent call last):
File "c:\Users\user\Documents\Team 1710\Code\GKC2022\test.py", line 26, in <module>
updateTeams()
File "c:\Users\user\Documents\Team 1710\Code\GKC2022\test.py", line 13, in updateTeams
canvas[x].itemconfig(teamCommentsButton[x], command = onClick)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2903, in itemconfigure
return self._configure(('itemconfigure', tagOrId), cnf, kw)
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) self._options(cnf))
_tkinter.TclError: invalid boolean operator in tag search expression
我希望能夠在 Tkinter 按鈕中更改命令的引數,但是當我嘗試執行此操作時出現此錯誤。我嘗試將引數更改為常量onClick = lambda : comments(10),并嘗試直接將方法呼叫作為命令command = comments(x 10),但都給了我同樣的錯誤
最重要的是,當我洗掉對代碼的呼叫時updateTeams(),代碼運行沒有錯誤,但無論我點擊哪個按鈕都會列印 5。我希望它根據我單擊的按鈕列印 0-5 的范圍,因為我為每個按鈕設定的引數取決于 x。
這是我洗掉視窗時視窗的樣子updateTeams()
uj5u.com熱心網友回復:
您的代碼中有兩個問題:
問題 1
按鈕不是畫布的專案。
您必須將按鈕視為常規 tkinter 小部件并使用配置:
teamCommentsButton[x].configure(command=onClick)
如果您希望按鈕實際位于畫布內,則必須將其添加到另一個框架并使用以下方法將該框架作為專案添加到視窗中:
canvas[x].create_window((20, 20), window=buttonFrame)
問題 2
在回圈中創建的 Python lambda 函式將執行相同的函式。這意味著您在 updateTeams() 中的 lambda 將始終使用 x = 15。這可以通過使用自己的函式來創建 lambda 來避免:
def create_lambda(x):
return lambda: comments(x 10)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462089.html
