Python Tkinter会创建意外的附加空白窗口
我正在使用Python3.5创建一个简单的GUI,它通过Python Tkinter会创建意外的附加空白窗口,python,user-interface,tkinter,Python,User Interface,Tkinter,我正在使用Python3.5创建一个简单的GUI,它通过文本框接收用户的信息,然后保存到.txt文件中 我注意到以下几点: 启动时会自动单击保存按钮,但再次单击不会产生任何效果 前景中会出现另一个名为tk的空白窗口 这是我的第一个GUI-python应用程序,非常感谢它的简单性和耐心 代码如下: #Program by Fares Al Ghazy started 20/5/2017 #Python script to assign key combinations to bash comman
文本框
接收用户的信息,然后保存到.txt
文件中
我注意到以下几点:
保存按钮
,但再次单击不会产生任何效果李>
#Program by Fares Al Ghazy started 20/5/2017
#Python script to assign key combinations to bash commands, should run in the background at startup
#Since this program is meant to release bash code, it is obviously non-system agnostic and only works linux systems that use BASH
#Further versions which support more OSs may come to life
#This is one file which only creates the GUI, another file is needed to use the info taken by this program
import tkinter as tk
#function to write to file
def SaveFunction(e1,e2):
print("opening file")
file = open("BinderData.txt","a")
combo = e1.get()
print("combo =" + combo)
performed = e2.get()
print("action = " + performed)
print("Writing to file")
file.write(combo)
file.write(performed)
print("closing file")
file.close()
print("file closed")
class MainFrame(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
#create GUI to take in key combinations and bash codes, then save them in file
root = tk.Tk() # create new window
root.wm_title("Key binder") #set title
#create labels and text boxes
KeyComboLabel = tk.Label(root,text = "Key combination = ")
KeyComboEntry = tk.Entry(root)
ActionLabel = tk.Label(root, text = "Command to be executed = ")
ActionEntry = tk.Entry(root)
#place widgets in positions
KeyComboLabel.grid(row=0,column =0,sticky = tk.E)
ActionLabel.grid(row=1,column =0, sticky = tk.E)
KeyComboEntry.grid(row=0,column =1)
ActionEntry.grid(row=1,column =1)
#create save button
SaveButton= tk.Button(root,text = "save")
SaveButton.grid(row=2,column =2, sticky = tk.E , command = SaveFunction(KeyComboEntry,ActionEntry))
app = MainFrame()
app.mainloop()
save函数
回调,并将结果绑定到命令
参数;请尝试使用lambda
表达式。另外,命令
参数必须转到构造函数,而不是布局函数
SaveButton= tk.Button(root,text = "save", command = lambda: SaveFunction(KeyComboEntry,ActionEntry))
SaveButton.grid(row=2,column =2, sticky = tk.E )
Tk
实例,因此获得了额外的空窗口,第一个是扩展Tk
的MainFrame
本身,第二个是在\uuu init\uuu
中创建的Tk()
。不要创建另一个Tk
,只需使用self
作为root
:
root = self # or change all "root" to "self" in the code below
或者没有大型机
extendTk
关于
命令
回调部分和lambda
的更多说明。正如我所说的,问题在于执行函数,然后将该执行的结果绑定到命令
。为了更清楚地说明这一点,command=SaveFunction(KeyComboEntry,ActionEntry)
与
cmd = SaveFunction(KeyComboEntry, ActionEntry)
SaveButton= tk.Button(root, text="save", command=cmd)
这显然不是你想要的。如果要调用一个没有参数的函数,只需使用
command=SaveFunction
而不使用()
,这样就不会调用函数,而是使用函数本身作为参数,但是由于SaveFunction
需要参数,因此必须定义一个内嵌的lambda
,调用SaveFunction
,它本身不需要任何参数。工作得很好,解释得很好,谢谢。你能详细说明一下兰姆达的部分吗?@FaresAlGhazy你到底需要知道什么command
需要一个函数,而lambda
是一种在线定义函数的方法。再次感谢,我想我只是不明白为什么需要在线定义它,而我已经在应用程序顶部定义、声明和实现了它?