gpt4 book ai didi

python - 使用 .grid 时无法在 Tkinter 中调用单选按钮

转载 作者:行者123 更新时间:2023-12-01 06:21:42 25 4
gpt4 key购买 nike

我正在尝试在 tkinter 中创建一组单选按钮,但在创建它们后无法调用它们。当我使用.pack()时,可以调用按钮,但是当使用.grid时,按钮无法调用。

def initialize():
Label(window,text = "Customer Name").grid(column = 0, row = 0)
customerName = StringVar()
nameEntry = Entry(window,textvariable = customerName)
nameEntry.grid(column = 1, row = 0)
def firstPizza():
Label(window,text = "Pizza 1").grid(column = 0,row = 1)
pizzaCost = DoubleVar() #12 and 10
largeButton = Radiobutton(window,text = "Large $15.95",value = 15.95,variable = pizzaCost)
mediumButton = Radiobutton(window,text = "Medium $12.95",value = 12.95, variable = pizzaCost)
smallButton = Radiobutton(window,text = "Small $10.95",value = 10.95, variable = pizzaCost)
largeButton.grid(column = 0,row = 2)
largeButton.invoke()
mediumButton.grid(column = 1, row = 2)
smallButton.grid(column = 2, row = 2)


firstPizza()

这行largeButton.invoke()没有执行其预期目的,并且根本没有调用任何东西。

最佳答案

问题是 pizzaCost 是一个局部变量。调用有效,但随后变量被垃圾收集,并且值被丢弃。

如果将变量设置为全局变量,则对 invoke 的调用将起作用。鉴于您可能希望稍后能够访问该值,因此您几乎必须将其设为全局,因为您没有使用类。

在以下示例中,请注意 pizzaCost 如何在 firstPizza 内部定义为全局。

from tkinter import *
def initialize():
Label(window,text = "Customer Name").grid(column = 0, row = 0)
customerName = StringVar()
nameEntry = Entry(window,textvariable = customerName)
nameEntry.grid(column = 1, row = 0)
def firstPizza():
global pizzaCost
Label(window,text = "Pizza 1").grid(column = 0,row = 1)
pizzaCost = DoubleVar() #12 and 10
largeButton = Radiobutton(window,text = "Large $15.95",value = 15.95,variable = pizzaCost)
mediumButton = Radiobutton(window,text = "Medium $12.95",value = 12.95, variable = pizzaCost)
smallButton = Radiobutton(window,text = "Small $10.95",value = 10.95, variable = pizzaCost)
largeButton.grid(column = 0,row = 2)
largeButton.invoke()
mediumButton.grid(column = 1, row = 2)
smallButton.grid(column = 2, row = 2)


firstPizza()

window = Tk()
initialize()
window.mainloop()

关于python - 使用 .grid 时无法在 Tkinter 中调用单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60326888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com