当我按下矩形(功能门1)时,我想要显示两个按钮,每个按钮都会给我的全局变量CHANGED提供不同的真值。 问题是我在对齐方面遇到了麻烦。按钮总是出现在我当前窗口的附加部分,我希望它们显示在我当前窗口的顶部
from tkinter import Tk, Canvas, Button
CHANGED = False
def options():
global window
button1 = Button(window, text='Click to change door')
button1.bind("<Button-1>", change)
button1.pack(side='top')
button2 = Button(window, text='Click to keep door')
button2.bind("<Button-1>", keep)
button2.pack(side='top')
def change(*args):
global CHANGED
CHANGED = True
def keep(*args):
global CHANGED
CHANGED = False
def door1(*args):
options()
window = Tk()
canvas = Canvas(window, width=600, height=500)
square1 = canvas.create_rectangle(50, 500, 150, 200, fill="blue", tags="open_door_1")
canvas.tag_bind("open_door_1", "<Button-1>", door1)
canvas.pack()
window.mainloop()
如何更改?
答案 0 :(得分:1)
您可以使用grid
来实现这一目标,方法是定义row
来放置小部件:
from tkinter import Tk, Canvas, Button
CHANGED = False
def options():
button1 = Button(window, text='Click to change door')
button1.bind("<Button-1>", change)
button1.grid(row=0, sticky='w')
button2 = Button(window, text='Click to keep door')
button2.bind("<Button-1>", keep)
button2.grid(row=1, sticky='w')
def change(*args):
global CHANGED
CHANGED = True
def keep(*args):
global CHANGED
CHANGED = False
def door1(*args):
options()
window = Tk()
canvas = Canvas(window, width=600, height=500)
square1 = canvas.create_rectangle(50, 500, 150, 200, fill="blue", tags="open_door_1")
canvas.tag_bind("open_door_1", "<Button-1>", door1)
canvas.grid(row=2)
window.mainloop()
编辑:
在窗口小部件出现时防止窗口大小调整的解决方案,您可以使用如下所示的rowconfigure
方法并指定几何图形:
另外,还有另外一点需要解决:您应该注意按钮的创建,每次在画布上单击都会创建另外两个小部件(可见或不可取决于布局)。 功能模式可能不是最好处理它,你需要将按钮定义为全局变量,只有在它们尚未显示时才创建它们:
from tkinter import Tk, Canvas, Button
CHANGED = False
button1 = None
button2 = None
def options():
global button1, button2
button1 = Button(window, text='Click to change door')
button1.bind("<Button-1>", change)
button1.grid(row=0, sticky='w')
button2 = Button(window, text='Click to keep door')
button2.bind("<Button-1>", keep)
button2.grid(row=1, sticky='w')
def change(*args):
global CHANGED
CHANGED = True
def keep(*args):
global CHANGED
CHANGED = False
def door1(*args):
if button1 is None and button2 is None:
options()
window = Tk()
window.geometry("600x600")
window.rowconfigure(2,weight=1)
canvas = Canvas(window, width=600, height=500)
square1 = canvas.create_rectangle(50, 500, 150, 200, fill="blue", tags="open_door_1")
canvas.tag_bind("open_door_1", "<Button-1>", door1)
canvas.grid(row=2,sticky='s')
window.mainloop()