社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

frame.quit在python中的用法

E. van der Linden • 5 年前 • 1541 次点击  

我目前正在使用python 3,并且正在编写我的第一个GUI程序。我不想将tkinter导入为: from tkinter import * 但是,我想把它作为 import Tkinter 因为我了解模块的工作方式。

在下面的代码中,我的退出按钮不起作用。为什么不呢?

import tkinter


class Main_Frame:

    def __init__(self, welk_window):
        top_Frame = tkinter.Frame(welk_window, width = "1", height = "1") 
        top_Frame.pack()

        self.Button_start = tkinter.Button(top_Frame, text = "Start", fg ="green", command=self.startMessage)
        self.Button_start.pack(side=tkinter.LEFT)

        self.Button_quit = tkinter.Button(top_Frame, text = "Quit", fg ="red", command=Frame.quit)
        self.Button_quit.pack(side=tkinter.LEFT)

    def startMessage(self):
        print("Start")


root = tkinter.Tk()     
master_window = Main_Frame(root) 
root.mainloop()

我做错什么了?我知道这与调用属性frame.quit有关。我试过用 Tkinter.Frame.quit 但这也不管用。事先谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38543
 
1541 次点击  
文章 [ 1 ]  |  最新文章 5 年前
abarnert
Reply   •   1 楼
abarnert    6 年前

你说得对,你必须给班级命名 tkinter.Frame 而不是仅仅 Frame

你也是对的,这不会解决任何问题。

因为根本问题是需要在 框架 实例 ,不是在 框架

幸运的是,您已经准备好了 框架 实例,从这行:

    top_Frame = tkinter.Frame(welk_window, width = "1", height = "1") 

因此,您可以使用它:

    self.Button_quit = tkinter.Button(top_Frame, text = "Quit", fg ="red", 
                                      command=top_Frame.quit)

但是,值得考虑一点重新设计。

通常,当您为tkinter创建类时,您希望使对象直接成为小部件,或者成为小部件的控制器。你的 Main_Frame 对象只是在初始化时创建一个框架小部件,然后忘记它,所以实际上两者都不是。


使 主框架 成为一个框架,只是继承自 框架 和使用 self 你会用到的任何地方 top_Frame :

class Main_Frame(tkinter.Frame):

    def __init__(self, welk_window):
        super().__init__(welk_window, width = "1", height = "1") 
        self.pack()

        self.Button_start = tkinter.Button(self, text = "Start", fg ="green", command=self.startMessage)
        self.Button_start.pack(side=tkinter.LEFT)

        self.Button_quit = tkinter.Button(self, text = "Quit", fg ="red", command=self.quit)
        self.Button_quit.pack(side=tkinter.LEFT)

    def startMessage(self):
        print("Start")

要使其成为帧控制器,只需存储 顶部框架 作为一个属性,使用相同的方法 Button_start :

class Main_Frame:

    def __init__(self, welk_window):
        self.top_Frame = tkinter.Frame(welk_window, width = "1", height = "1") 
        self.top_Frame.pack()

        self.Button_start = tkinter.Button(top_Frame, text = "Start", fg ="green", command=self.startMessage)
        self.Button_start.pack(side=tkinter.LEFT)

        self.Button_quit = tkinter.Button(top_Frame, text = "Quit", fg ="red", command=self.top_Frame.quit)
        self.Button_quit.pack(side=tkinter.LEFT)

    def startMessage(self):
        print("Start")