【问题标题】:gui class with two programs带有两个程序的 gui 类
【发布时间】:2019-05-04 02:29:59
【问题描述】:

我正在尝试在一个按钮上制作一些示例 GUI tkinter 尝试服务器状态,如果它有效,单击按钮启动后它会破坏 gui 并启动一些向我发送文件文本的功能。我已经制作了gui和服务器连接测试按钮,但不知道如何销毁gui和启动功能。非常感谢:)

from tkinter import *
import requests, os

class form():
root = Tk()
wel = Label(root,text="Welcome")
serv = Entry(root,width=40)

def checkConn():
    if(requests.get(serv.get()).status_code==200):
        print("Succesfull")

def start(self):
    root.destroy()

prov = Button(root,text="Proveri",width=35, command = checkConn)
zap =  Button(root, text ="Zapocni",width=35,command =start)

wel.pack()
serv.pack()
prov.pack()
zap.pack()

root.mainloop()




form()

【问题讨论】:

    标签: python oop user-interface logging tkinter


    【解决方案1】:

    我建议使用__init__() 函数来设置 GUI 以及类变量。我以我编写它的方式重写了您的代码,但没有请求位,只是为了显示 GUI 功能。

    from tkinter import *
    import requests
    
    class form():
        def __init__(self, master):
            self.master = master
            self.serv_text = StringVar()    # StringVar to hold entry value
            wel = Label(root, text="Welcome")
            serv = Entry(root, width=40, textvariable=self.serv_text)
            prov = Button(self.master, text="Proveri", width=35,
                          command=self.checkConn)
            zap =  Button(self.master, text ="Zapocni", width=35,
                          command=self.start)
            wel.pack()
            serv.pack()
            prov.pack()
            zap.pack()
    
        def checkConn(self):
            if(requests.get(self.serv_text.get()).status_code==200):
                print("Succesfull")
            else:
                print('miss')
    
        def start(self):
            self.master.destroy()
    
    root = Tk()
    form(root)
    root.mainloop()
    

    您将在Best way to structure a tkinter application 中找到更多示例和讨论。

    【讨论】:

    • 非常感谢,但我仍然有 smtg,当我尝试使用 get 方法“def checkConn(self):print(self.serv.get())”时会导致错误 AttributeError: 'form ' 对象没有属性 'serv' @figbeam
    • 您需要将“serv”设置为 instance 变量,否则函数将找不到它。我已经更新了我的示例,现在应该可以正常工作了。
    • 好的,但是当我创建实例变量时,他们每次都为空字符串获取()我,因为我需要输入字符串,然后执行一些类似检查请求的功能:)
    • 啊,我不太明白你的意思。我已经更新了我的答案,现在我使用 StringVar 从条目中读取,它工作正常。然而;如果我输入一个无效的 URL,我会得到一个错误。您必须验证条目或使用try 子句来处理。
    • 如果原始问题得到解答,您应该打开一个新问题,而不是添加到旧问题中。另外,我从未使用过 pynput 或日志记录,所以在这方面我不是你的人。
    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2015-12-30
    • 2023-03-12
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    相关资源
    最近更新 更多