首页 > 解决方案 > Python 3 Tkinter:弹出窗口不显示

问题描述

我有两个由同一个按钮触发的弹出窗口:一个有一个进度条、一个标签和一个按钮。另一个只有 2 个标签和一个按钮。如果我评论进度条的更新功能:不会显示任何弹出窗口。如果我尝试只显示第二个(没有进度条)它不会显示。我只能同时显示两个,我只想显示第二个(没有进度条)

这是第一个弹出窗口的代码:

def sim_process_bar(self):
        self.popup_process = Tk()
        self.popup_process.wm_title("Simulation process...")
        self.progressBar = ttk.Progressbar(self.popup_process, orient = 'horizontal', length = 286, mode = 'determinate')
        self.progressBar['maximum'] = 100
        self.stopBtn = Button(self.popup_process, text="Stop Simulation", command = self.popup_process.destroy)
        self.progressBar.grid(column = 1, row = 1, pady = 10)
        self.stopBtn.grid(column = 1, row = 2)

        self.labelPercentage = Label(self.popup_process, text="Percentage complete : 0% ")
        self.labelPercentage.grid(column = 1, row = 3, pady = 10)

    def update_value_process_bar(self, value):
        self.progressBar['value'] = value
        self.progressBar.update()

第二个弹出窗口的代码:

def process_feedback(self):
        self.popupFeedback = Tk()
        self.popupFeedback.wm_title("Simulation process...")
        self.labelTimestep = Label(self.popupFeedback, text="Current timestep : ")
        self.labelTimestep.grid(column = 0 , row = 1, pady = 10)

        self.labelPercentage2 = Label(self.popupFeedback, text="Percentage complete : ")
        self.labelPercentage2.grid(column = 0, row = 2, pady = 10)

        self.Btnstop = Button(self.popupFeedback, text="Stop Simulation", command = self.popupFeedback.destroy)
        self.Btnstop.grid(column = 0, row = 3)

我在循环开始之前调用该函数,然后在同一个循环内更新值:

更新 :

if(round(k/self.total_timestep_of_simulation*100,1).is_integer()):
    self.update_value_process_bar(k/self.total_timestep_of_simulation*100)
    self.labelPercentage['text'] = "Percentage complete : " + str(round(k/self.total_timestep_of_simulation*100,1)) + "%"
#UPDATE POPUP FEEDBACK
self.labelTimestep['text'] = "Current timestep : " + str(data_update.strftime("%b %d %Y %H:%M:%S"))
self.labelPercentage2['text'] = "Percentage complete : " + str(round(k/self.total_timestep_of_simulation*100,1)) + "%"

所以如果我评论“self.update_value”...函数,屏幕上什么也没有显示,如果我只尝试显示第二个,也没有任何显示。我确定这是一个愚蠢的问题,但我正在努力解决这个问题......

标签: pythonpython-3.xtkinter

解决方案


您的代码没问题,但请尝试删除该行self.stopBtn = Button(self...或将其替换为

    self.stopButton = Button(self.popup_process,
                             text="Stop Simulation",
                             command = self.destroy_popup)

并添加

def destroy_popup(self):
    self.popup_process.destroy()

另一个弹出窗口也一样:

    self.Btnstop = Button(self.popupFeedback,
                          text="Stop Simulation",
                          command = self.destroy_popup)
    ...

def destroy_popup(self):
    self.popupFeedback.destroy()

有时按钮“建立连接”到它所连接的控件。在这个例子中,self.popup_process.destroy是一个包含在Tkinter模块中的循环。所以按钮执行该命令。把它放在 a 中def可以避免这种情况。

这仅对某些版本有效。也许您正在使用的就是其中之一。否则我不知道。


推荐阅读