Tkinter Python代码中的无限循环

0 投票
1 回答
807 浏览
提问于 2025-04-17 18:25

我正在尝试运行一个简单的Tkinter程序,点击一个按钮时可以打开另一个程序。下面是我的代码。我使用一个命令来调用一个程序,然后这个程序再调用一个Fortran程序。然而,当我点击按钮时,虽然程序打开了,但我调用的程序的菜单却陷入了无限循环……问题似乎出在button1Click这个模块里。

非常感谢任何帮助。

谢谢

from Tkinter import * 
import os, sys 
from win32com.client import Dispatch 
xlApp=Dispatch('Excel.Application') 
_PSSBINPATH=r"C:\Program Files\PTI\PSSE32\PSSBIN" 
os.environ['PATH']=_PSSBINPATH+';'+os.environ['PATH'] 
sys.path.insert(0,_PSSBINPATH) 
import redirect; redirect.psse2py() 
import psspy 

class MyApp: 
    def __init__(self, parent): 
        self.myParent = parent  ### (7) remember my parent, the root 
        self.myContainer1 = Frame(parent) 
        self.myContainer1.pack() 

        self.button1 = Button(self.myContainer1) 
        self.button1.configure(text="OK", background= "green") 
        self.button1.pack(side=LEFT) 
        self.button1.bind("<Button-1>", self.button1Click) ### (1) 

        self.button2 = Button(self.myContainer1) 
        self.button2.configure(text="Cancel", background="red") 
        self.button2.pack(side=RIGHT) 
        self.button2.bind("<Button-1>", self.button2Click) ### (2) 

    def button1Click(self,event):    ### (3) 
        psspy.runiplanfile(r"C:\MNTACT\Contingency Program\work\contingency-31-4.irf") 
        if self.button1["background"] == "green": ### (4) 
            self.button1["background"] = "yellow" 
        else: 
            self.button1["background"] = "green" 

    def button2Click(self, event):  ### (5) 
        self.myParent.destroy()     ### (6) 


root = Tk() 
myapp = MyApp(root) 
root.mainloop() 

1 个回答

0

你为什么觉得出现了无限循环呢?我在button1Click里没看到任何循环,除非循环是在runiplanfile里。你是不是把“无限循环”这个词用来形容界面不响应了?

Tkinter是单线程的,只有通过事件循环才能处理事件。如果某个事件处理得很慢,界面就会卡住,直到这个事件处理完毕。如果你在执行一个外部程序并等待它完成,那么在这个程序运行期间,你的界面看起来就会像是冻结了一样。

撰写回答