gpt4 book ai didi

python - Tkinter (python 2.7.2) 需要帮助

转载 作者:太空宇宙 更新时间:2023-11-03 19:26:46 25 4
gpt4 key购买 nike

我正在尝试制作我的第一个 GUI 程序。问题是,我不知道如何制作主菜单,单击按钮后会切换到其中一个程序。

#Dev by Mkee
from Tkinter import *
import tkMessageBox
#Main Stuff
app = Tk()
app.title("Mkee's Tools")
app.geometry('300x200')

#modules
class Programs:
def Shuffle():
app2 = Tk()
app2.title("Shuffle")
app2.geometry('300x200')
app2.mainloop()


#end of modules

labelText = StringVar()
labelText.set('')
label1 = Label(app, textvariable=labelText, height=4)
label1.pack()

button1 = Button(app, text='Shuffle', width=30, command=Programs.Shuffle)
button1.pack(side='right', padx=5,pady=1)


app.mainloop()

我知道我做错了。我只是不知道该怎么做,所以我尝试了一下怎么可能。请帮助我。

最佳答案

  1. 您可以调用pack_forget()隐藏小部件,以及(稍后)打包以再次显示它们:

  2. Tkinter 是单线程的,mainloop 运行主事件循环。因此,您不应调用 mainloop 两次。

<小时/>
#Dev by Mkee
import Tkinter as tk
import sys

class Shuffle(object):
def __init__(self,master=None):
self.master=master
self.text=tk.Text(master)
def hide(self):
self.text.pack_forget()
def show(self):
self.text.pack(side=tk.LEFT, padx=5, pady=5)

class Buttons(object):
def __init__(self,master=None):
self.master=master
self.red = tk.Button(self.master, text="Red", bg="red", fg="white")
self.green = tk.Button(self.master, text="Green", bg="green", fg="black")
self.blue = tk.Button(self.master, text="Blue", bg="blue", fg="white")
def hide(self):
self.red.pack_forget()
self.green.pack_forget()
self.blue.pack_forget()
def show(self):
self.red.pack(side=tk.LEFT,expand=tk.YES,fill=tk.BOTH)
self.green.pack(side=tk.LEFT,expand=tk.YES,fill=tk.BOTH)
self.blue.pack(side=tk.LEFT,expand=tk.YES,fill=tk.BOTH)

class MainApp(object):
def __init__(self,master=None):
self.master=master
app=self.app=tk.Tk()
app.title("Mkee's Tools")
app.geometry('300x200')
self.shuffle=Shuffle(master)
self.buttons=Buttons(master)
self.current=None
menubar=tk.Menu(app)
program_menu=tk.Menu(menubar)
program_menu.add_command(label='Shuffle',
command=lambda: self.show(self.shuffle))
program_menu.add_command(label='Buttons',
command=lambda: self.show(self.buttons))
program_menu.add_command(label='Quit',command=sys.exit)
menubar.add_cascade(label='Programs', menu=program_menu)
app.config(menu=menubar)
def show(self,obj):
if self.current != obj:
try: self.current.hide()
except AttributeError: pass
self.current=obj
obj.show()

def main():
m=MainApp()
m.app.mainloop()

if __name__=='__main__':
main()

关于python - Tkinter (python 2.7.2) 需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7862621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com