[英]How to stop Python from executing script on import?
我有一個帶有一系列按鈕的基於Tkinter的GUI。 我希望這些按鈕之一可以在按下時從另一個腳本testExecute.py
執行命令(下面兩個腳本的代碼)。
現在,當我啟動GUI時,外部腳本功能似乎是在import
時執行的,而不是按按鈕時(按該按鈕也似乎不執行該功能)。 我做了一些研究,並將if __name__ == "__main__":
包含在testExecute.py
,但它仍在導入時在我的主腳本中執行。 有什么想法嗎?
響應以下問題的額外問題:如果我想將參數傳遞給函數怎么辦? 因為如果我包含參數,該函數將再次在導入時執行。 但是,如果不包含該參數,則在按下按鈕時會出現錯誤。
主腳本:
from tkinter import *
from tkinter.ttk import *
import testExecute as testEx
class mainGUI(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("GUIV0.1")
self.pack(fill=BOTH, expand=True)
self.columnconfigure(1, weight = 1)
self.columnconfigure(3, pad = 7)
self.rowconfigure(3, weight = 1)
self.rowconfigure(5, pad = 7)
lbl = Label(self, text = "Windows")
lbl.grid(sticky = W, pady=4, padx=5)
area = Text(self)
area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)
abtn = Button(self, text="Activate", command = testEx.testFunc())
abtn.grid(row=1, column=3)
cbtn = Button(self, text="Close")
cbtn.grid(row=2, column=3, pady=4)
hbtn = Button(self, text="Help")
hbtn.grid(row=5, column=0, padx=5)
obtn = Button(self, text="OK")
obtn.grid(row=5, column=3)
def main():
root = Tk()
app = mainGUI(root)
root.mainloop()
if __name__ == '__main__':
main()
testExecute.py:
def testFunc():
print("Test test test")
print("I do nothing, if you see this text, I am hiding in your code!")
if __name__ == "__main__":
testFunc()
創建按鈕時,您將直接執行該功能。 相反,您應該綁定到函數本身。 所以
abtn = Button(self, text="Activate", command = testEx.testFunc())
應該
abtn = Button(self, text="Activate", command = testEx.testFunc)
查看http://effbot.org/tkinterbook/button.htm 。
問題是您在初始化期間正在調用命令回調。 更改,
abtn = Button(self, text="Activate", command = testEx.testFunc())
至
abtn = Button(self, text="Activate", command = testEx.testFunc)
你應該一切都好。 (請注意,在testFunc之后沒有括號)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.