使用tkinter分配全局变量并销毁gui

时间:2015-06-02 21:52:13

标签: python user-interface tkinter arcgis esri

我一直在编写年度数据验证程序,需要一些用户输入,并决定采用tkinter路线。我已经为其中一个用户输入屏幕创建了界面,并且必须创建其他界面,但是我在选择完成后会出现一些破坏窗口的问题,以及变量的全球化。

理想情况下,程序运行,窗口弹出,进行适当的属性选择,该按钮上的文本传递给"分配" function,它创建一个在我的程序中使用的全局变量,窗口​​消失。

现在,运行此代码会导致错误:" TclError:无法调用"按钮"命令:应用程序已被销毁"。

如果我注释掉" mGui.destroy()"我可以选择一个按钮并手动关闭窗口,但是" DRN"变量传递给变量" x"无论如何!

import sys
from Tkinter import *

def assign(value):
    global x
    x = value
    mGui.destroy()

mGui = Tk()
mGui.geometry("500x100+500+300")
mGui.title("Attribute Selection Window")

mLabel = Label(mGui, text = "Please select one of the following attributes to assign to the selected Convwks feature:").pack()

mButton = Button(mGui, text = "CON", command = assign("CON")).pack()
mButton = Button(mGui, text = "MS", command = assign("MS")).pack()
mButton = Button(mGui, text = "DRN", command = assign("DRN")).pack()

mGui.mainloop()     #FOR WINDOWS ONLY

奖金问题:将所有按钮放在同一行,两者之间留有空格,同时保持居中。

1 个答案:

答案 0 :(得分:2)

代码的问题在于,在添加按钮命令时无法调用函数。你不能写Button(command=function()),你必须写Button(command=function)。如果你想将一个参数传递给一个函数,你必须这样做:

而不是:

mButton = Button(mGui, text = "CON", command = assign("CON")).pack()
mButton = Button(mGui, text = "MS", command = assign("MS")).pack()
mButton = Button(mGui, text = "DRN", command = assign("DRN")).pack()

你必须写:

mButton = Button(mGui, text = "CON", command = lambda: assign("CON")).pack()
mButton = Button(mGui, text = "MS", command = lambda: assign("MS")).pack()
mButton = Button(mGui, text = "DRN", command = lambda: assign("DRN")).pack()

如果要将所有按钮放在同一行,可以使用以下代码:

import sys
from Tkinter import *

def assign(value):
    global x
    x = value
    mGui.destroy()

mGui = Tk()
mGui.geometry("500x100+500+300")
mGui.title("Attribute Selection Window")

frame1 = Frame(mGui)
frame1.pack()

mLabel = Label(frame1, text = "Please select one of the following attributes to assign to the selected Convwks feature:").grid(row=0, column=0)

frame2 = Frame(mGui)
frame2.pack()


mButton = Button(frame2, text = "CON", command = lambda: assign("CON")).grid(row=0, column=0, padx=10)
mButton = Button(frame2, text = "MS", command = lambda: assign("MS")).grid(row=0, column=1, padx=10)
mButton = Button(frame2, text = "DRN", command = lambda: assign("DRN")).grid(row=0, column=2, padx=10)
mGui.mainloop()     #FOR WINDOWS ONLY