我正在尝试编写游戏。到目前为止,我已经制作了一个按钮网格,但是我似乎无法使按钮按我希望的方式工作。我认为问题出在x和y没有连接到实际按钮上,但是我已经尝试了所有方法,但似乎无法使其正常工作。以下是我的最新尝试。
import tkinter as tk
jeopardy = tk.Tk()
jeopardy.geometry("2000x1000")
jeopardy.configure(background="blue")
#------------Questions---------------
def questions():
global x
global y
global sort
for sort in (x, y):
if x == 0:
if y == 0:
extra_window = tk.Toplevel(jeopardy)
label2 = tk.Label(extra_window, text="question")
label2.pack()
elif y == 1:
extra_window = tk.Toplevel(jeopardy)
label3 = tk.Label(extra_window, text="question")
label3.pack()
#etc
#------------Buttongrid---------------
tk.Grid.rowconfigure(jeopardy, 0, weight=1)
tk.Grid.columnconfigure(jeopardy, 0, weight=1)
frame= tk.Frame(jeopardy)
frame.grid(row=0, column=0, sticky="nsew")
for x in range(5):
tk.Grid.rowconfigure(frame, x, weight=1)
for y in range(5):
tk.Grid.columnconfigure(frame, y, weight=1)
text = 100*(y+1)
btn = tk.Button(frame, text=str(text), command=questions)
sort = btn.grid(column=x, row=y, sticky="nsew")
jeopardy.mainloop()
答案 0 :(得分:1)
您有很多重复且无用的globals
。您可以使用lambda
函数将参数传递给回调函数。我编辑了您的代码以说明问题:
import tkinter as tk
jeopardy = tk.Tk()
jeopardy.geometry("1000x500")
jeopardy.configure(background="blue")
#------------Questions---------------
def questions(x, y):
questiontext = f"question{x}{y}"
extra_window = tk.Toplevel(jeopardy)
lab = tk.Label(extra_window, text=questiontext)
lab.pack()
#------------Buttongrid---------------
tk.Grid.rowconfigure(jeopardy, 0, weight=1)
tk.Grid.columnconfigure(jeopardy, 0, weight=1)
frame= tk.Frame(jeopardy)
frame.grid(row=0, column=0, sticky="nsew")
for x in range(5):
tk.Grid.rowconfigure(frame, x, weight=1)
for y in range(5):
tk.Grid.columnconfigure(frame, y, weight=1)
text = 100*(y+1)
btn = tk.Button(frame, text=str(text), command=lambda x=x, y=y: questions(x, y))
btn.grid(column=x, row=y, sticky="nsew")
jeopardy.mainloop()
lambda x=x , y=y : ...
避免使用x,y始终是@Herny Yik的评论所提及的循环的最后一个值。
答案 1 :(得分:1)
我不知道您打算通过创建新的Toplevel
窗口来做什么,但是当您单击Button
时,以下内容将更改它们(不依赖全局变量):
import tkinter as tk
jeopardy = tk.Tk()
jeopardy.geometry("800x800")
jeopardy.configure(background="blue")
ROWS, COLS = 5, 5
# You'll want to populate this with real questions.
QUESTIONS = [['question {:2d}'.format(j*COLS+i) for i in range(1,COLS+1)]
for j in range(ROWS)]
tk.Grid.rowconfigure(jeopardy, 0, weight=1)
tk.Grid.columnconfigure(jeopardy, 0, weight=1)
frame = tk.Frame(jeopardy)
frame.grid(row=0, column=0, sticky="nsew")
for x in range(ROWS):
tk.Grid.rowconfigure(frame, x, weight=1)
for y in range(COLS):
tk.Grid.columnconfigure(frame, y, weight=1)
text = 100*(y+1)
btn = tk.Button(frame, text=str(text))
btn.grid(column=x, row=y, sticky="nsew")
def show_question(btn=btn, x=x, y=y):
btn.config(text=QUESTIONS[x][y])
btn.config(command=show_question)
jeopardy.mainloop()