This is my Copy&Paste program:
from tkinter import *
import Pmw
class CopyTextWindow(Frame):
def __init__(self):
Frame.__init__(self)
Pmw.initialise()
self.pack(expand=YES, fill=BOTH)
self.master.title("ScrolledText Demo")
self.frame1=Frame(self, bg="White")
self.frame1.pack(expand=YES, fill=BOTH)
self.text1=Pmw.ScrolledText(self, text_width=25, text_height=12, text_wrap=WORD,
hscrollmode="static", vscrollmode="static")
self.text1.pack(side=LEFT, expand=YES, fill=BOTH, padx=5, pady=5)
options = ["Copy", "Paste"]
self.selectedOption = StringVar()
self.menu = Menu(self.frame1, tearoff=0)
for option in options:
self.menu.add_radiobutton( label=option, variable=self.selectedOption,
command=self.ExecuteOption)
self.text1.bind("<Button-3>", self.popUpMenu)
def popUpMenu(self, event):
self.menu.post(event.x_root, event.y_root)
def ExecuteOption(self):
if self.selectedOption.get()=="Copy":
self.CopiedText=self.text1.get(SEL_FIRST, SEL_LAST)
else:
self.text1.settext( self.text1.get()+self.CopiedText)
def main():
CopyTextWindow().mainloop()
if __name__=="__main__":
main()
In this program, I want to make a GUI, that in it you can copy and paste text that you have selected. when you press the right mouse button, a little menu with the Copy and Paste options.
The program opens up, but when I press the right mouse button, no menu appears. Python also doesn't complain with an error.
I need to understand my mistake in this code.
For a reason I ignore, the event doesn't seem to be triggered when the bind is on the Text or on the Frame, but it works when it's on the main window:
from tkinter import *
import Pmw
class CopyTextWindow(Frame):
def __init__(self, master=None):
# I've added a master option to pass to the frame
Frame.__init__(self, master)
Pmw.initialise()
self.pack(expand=YES, fill=BOTH)
self.master.title("ScrolledText Demo")
self.frame1=Frame(self, bg="White")
self.frame1.pack(expand=YES, fill=BOTH)
self.text1=Pmw.ScrolledText(self, text_width=25, text_height=12, text_wrap=WORD,
hscrollmode="static", vscrollmode="static")
self.text1.pack(side=LEFT, expand=YES, fill=BOTH, padx=5, pady=5)
options = ["Copy", "Paste"]
self.selectedOption = StringVar()
self.menu = Menu(self.frame1, tearoff=0)
for option in options:
self.menu.add_radiobutton( label=option, variable=self.selectedOption,
command=self.ExecuteOption)
def popUpMenu(self, event):
print("ok")
self.menu.post(event.x_root, event.y_root)
def ExecuteOption(self):
if self.selectedOption.get()=="Copy":
self.CopiedText=self.text1.get(SEL_FIRST, SEL_LAST)
else:
self.text1.settext( self.text1.get()+self.CopiedText)
def main():
# main window
root = Tk()
ctw = CopyTextWindow(root)
# bind on the main window
root.bind("<Button-3>", ctw.popUpMenu)
root.mainloop()
if __name__=="__main__":
main()
Related
I am working on a game called 'Flag Quiz' using tkinter. I have a script called mainmenu where I can choose between an easy mode and a hard mode. If I click on one of the buttons the recent mainmenu window disappears and a new tkinter window opens.
Here is my mainmenu script:
from tkinter import *
import tkinter as tk
from hardmode import HardApp
from easymode import EasyApp
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('600x600')
self.resizable(0,0)
self.make_widgets()
def make_widgets(self):
self.background = PhotoImage(file = './background.png')
self.label = Label(self, image=self.background)
self.label.place(x=0, y=0, relwidth=1, relheight=1)
self.easy = Button(self, text="Easy Mode", height=2, width=6, font=('default', 20), command=self.play_easy)
self.hard = Button(self, text="Hard Mode", height=2, width=6, font=('default', 20), command=self.play_hard)
self.easy.place(relx=0.5, rely=0.45, anchor=CENTER)
self.hard.place(relx=0.5, rely=0.55, anchor=CENTER)
def play_easy(self):
self.withdraw()
self.app = EasyApp()
#self.app.start()
def play_hard(self):
self.withdraw()
self.app = HardApp()
#self.app.start()
def start(self):
self.mainloop()
TitleScreen().start()
And here is my easy mode script:
import tkinter as tk
from tkinter import *
import random
import os
import json
class EasyApp(tk.Toplevel):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('')
self.resizable(0,0)
self.score = 0
self.create_widgets()
def create_widgets(self):
# variables
self.user_guess = StringVar(self)
self.text = StringVar(self)
self.text.set(" ")
# initial image
self.scoretext = Label(self, text="Score: ").pack(side='top', fill='x')
self.scorevalue = Label(self, text=self.score).pack(side='top', fill='x')
self.file = random.choice(os.listdir('pngs'))
self.randimg = PhotoImage(file='pngs/{}'.format(self.file))
self.randimg = self.randimg.subsample(2, 2)
self.panel = Label(self, image=self.randimg)
self.panel.pack()
self.country, self.ext = self.file.split('.')
self.countries = self.load_lookup()
self.countryname = [country for country in self.countries if country['alpha2'] == self.country]
self.s = []
for i in range(0,3):
country = random.choice(self.countries)
self.s.append(country['de'])
self.s.append(self.countryname[0]['de'])
random.shuffle(self.s)
self.btndict = {}
for i in range(4):
self.btndict[self.s[i]] = Button(self, text=self.s[i], height=2, width=35, font=('default', 20), command=lambda j=self.s[i]: self.check_input(j))
self.btndict[self.s[i]].pack()
def check_input(self, d):
if d != self.countryname[0]['de']:
print("Falsch")
else:
self.score += 5
for widget in self.winfo_children():
widget.destroy()
self.create_widgets()
def load_lookup(self):
with open('lookup.json') as file:
self.obj = file.read()
self.countryobj = json.loads(self.obj)
return self.countryobj
# def start(self):
# self.mainloop()
After clicking the close button (the default button on windows/osx to close a window) the window from my easy mode app disappears but PyCharm says that my program is still running.
I made some investigations and removed the self.withdraw() function in the function play_easy(self) in my mainmenu script. So now the mainmenu is still open after I click on the easy mode button. If I'm closing both windows now, the program fully ends.
Replacing self.withdraw() with self.destroy() is not working. The main menu is closed, but a new empty window opens instead.
Any suggestions on how to handle this problem so that my program fully ends if I click the close button within the easy/hard mode window?
You have two windows - main window created with Tk and subwindow created with Toplevel. When you use close button to close main window then it should also close all subwindows but when you close subwindow then it doesn't close main window (parent window) but only own subwindows - because usually it can be useful to display again main window to select other options and open again subwindow.
One of the methods is to destroy first window and use Tk to create new window.
But in this method you can't use some button in second window to go back to first window - and sometimes it can be problem. Even if you create again first window then it will not remeber previous values (if you have some Entry or other widgets to set values)
# from tkinter import * # PEP8: `import *` is not preferred`
import tkinter as tk
class EasyApp(tk.Tk): # use `Tk` instead of `Toplevel`
def __init__(self):
super().__init__()
self.scoretext = tk.Label(self, text="EasyApp")
self.scoretext.pack()
#def start(self):
# self.mainloop()
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.button = tk.Button(self, text="Easy Mode", command=self.play_easy)
self.button.pack()
def play_easy(self):
self.destroy() # destroy current window
self.app = EasyApp()
def start(self):
self.mainloop()
TitleScreen().start()
Other method is to use self.wm_protocol("WM_DELETE_WINDOW", self.on_close) to execute function on_close when you use close button and in this function destroy main window (master).
This way you can still use Button to go back to main window which will remember previous content.
# from tkinter import * # PEP8: `import *` is not preferred`
import tkinter as tk
class EasyApp(tk.Toplevel): # still use `Toplevel`
def __init__(self, master): # send main window as master/parent
super().__init__(master) # it will also set `self.master = master`
self.scoretext = tk.Label(self, text="EasyApp")
self.scoretext.pack()
self.button = tk.Button(self, text="Go Back", command=self.go_back)
self.button.pack()
# run `on_close` when used `close button`
#self.protocol("WM_DELETE_WINDOW", self.on_close)
self.wm_protocol("WM_DELETE_WINDOW", self.on_close)
def go_back(self):
self.destroy() # destroy only current window
self.master.deiconify() # show again main window
def on_close(self):
self.destroy() # destroy current window
self.master.destroy() # destroy main window
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.entry = tk.Entry(self)
self.entry.pack()
self.entry.insert('end', "You can change text")
self.button = tk.Button(self, text="Easy Mode", command=self.play_easy)
self.button.pack()
def play_easy(self):
self.withdraw()
self.app = EasyApp(self) # send main window as argument
def start(self):
self.mainloop()
TitleScreen().start()
Here's a fairly simple architecture for doing what you want. An application class is derived from Tk() which hides the default "root" window it normally displays and all the windows it does display are subclasses of a custom Toplevel subclass I've named BaseWin.
This class is just a Toplevel with its protocol for being delete (closed) set to call an a method named on_close(). This additional method simply destroys the current window before quits the application's mainloop() causing it to terminate.
The first window—an instance of the TitleScreen class—is displayed automatically when an instance of the application class is created. This window has two Buttons one labelled Easy Mode and the other Hard Mode. When one of them is clicked, an instance of the appropriate Toplevel subclass is created after the current window is removed by it call its destroy() method.
mainmenu.py
import tkinter as tk
from tkinter.constants import *
from tkinter import font as tkfont
from basewin import BaseWin
from easymode import EasyApp
from hardmode import HardApp
class SampleApp(tk.Tk):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('600x600')
self.resizable(FALSE, FALSE)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold")
self.withdraw() # Hide default root Tk window.
startpage = TitleScreen(self.master)
self.mainloop()
class TitleScreen(BaseWin):
def __init__(self, master):
super().__init__(master)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Start Page", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)
self.easy = tk.Button(self, text="Easy Mode", font=('default', 20),
command=self.play_easy)
self.hard = tk.Button(self, text="Easy Mode", font=('default', 20),
command=self.play_hard)
self.easy.pack()
self.hard.pack()
def play_easy(self):
self.destroy()
self.app = EasyApp(self.master)
def play_hard(self):
self.destroy()
self.app = HardApp(self.master)
if __name__ == '__main__':
SampleApp()
basewin.py
import tkinter as tk
from tkinter.constants import *
class BaseWin(tk.Toplevel):
def __init__(self, master):
super().__init__(master)
self.protocol("WM_DELETE_WINDOW", self.on_close)
def on_close(self):
self.destroy() # Destroy current window
self.master.quit() # Quit app.
easymode.py
import tkinter as tk
from tkinter.constants import *
from basewin import BaseWin
class EasyApp(BaseWin):
def __init__(self, master):
super().__init__(master)
self.title('Flag Quiz')
self.resizable(FALSE, FALSE)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Easy App", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)
hardmode.py
import tkinter as tk
from tkinter.constants import *
from basewin import BaseWin
class HardApp(BaseWin):
def __init__(self, master):
super().__init__(master)
self.title('Flag Quiz')
self.resizable(FALSE, FALSE)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Hard App", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)
Total noob can't make tkinter button bind to keyboard.
I've tried to bind they both in main() and in the init().
I've tried bunches of permutations of syntax. Nothing works.
I've tried around until the button(s) get focus and hitting then. NOTHING HAPPENS.
Anyone have the secret insider information on how to do it?
from tkinter import *
from tkinter.ttk import Frame, Button, Style
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
self.btn_convert.bind("<Return>", self.convert)
# -----------------------------------------------
def convert(self):
print("enter pressed")
# -----------------------------------------------
def quit(self):
self.root.destroy()
exit()
# -----------------------------------------------
def initUI(self):
self.master.title("Weight Converter")
self.pack(fill=BOTH, expand=True)
self.frame_btn = Frame(self)
self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
self.btn_convert.pack(side=LEFT, padx=5, pady=5)
self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
self.btn_close1.pack(side=LEFT, padx=5, pady=5)
def main():
root = Tk()
root.geometry("300x250+300+200")
app = Example()
root.bind("<Return>", lambda event: root.convert())
root.mainloop()
if __name__ == '__main__':
main()
Replace:
root.bind("<Return>", lambda event: root.convert())
with:
root.bind("<Return>", lambda event: app.convert())
or:
#in case you have multiple instances of Tk
app.bind("<Return>", lambda event: app.convert())
app.focus_set()
As convert is a method for Example instance(app) as opposed to Tk instance(root). Also, make sure that the object.bind is used on(root in above two lines and app onthe last line) has the focus by either manually focusing or calling object.focus_set().
Below is an example that prints "Enter" or "Escape" based on the keypress:
import tkinter as tk
class App(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.button = tk.Button(self, text="Event")
self.button.bind('<Return>', lambda evt : self.event_handler(True))
self.button.focus_set() # ensure initial focus is on the button
self.button.pack()
def event_handler(self, is_enter):
if is_enter:
my_string = "Enter"
else:
my_string = "Escape"
print(my_string)
if __name__ == '__main__':
root = tk.Tk()
app = App(root)
app.button.bind('<Escape>', lambda evt : app.event_handler(False))
app.pack()
root.mainloop()
Demo Example for all keys
Below demo should be displaying the pressed key for all keys:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def on_key_press(event):
global label
label['text'] = event.keysym
if __name__ == '__main__':
root = tk.Tk()
label = tk.Label(root)
root.bind('<KeyPress>', on_key_press)
label.pack()
root.mainloop()
To add a general "press Enter to run convert" binding, you should apply it to root. To add further focus-based bindings, you should apply them on a per-button basis, like so:
from tkinter import *
from tkinter.ttk import Frame, Button, Style
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
# -----------------------------------------------
def convert(self):
print("enter pressed")
# -----------------------------------------------
def quit(self):
print("quit pressed")
self.destroy()
exit()
# -----------------------------------------------
def initUI(self):
self.master.title("Weight Converter")
self.pack(fill=BOTH, expand=True)
self.frame_btn = Frame(self)
self.frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)
self.btn_convert=Button(self.frame_btn, text="Convert", command=self.convert)
self.btn_convert.pack(side=LEFT, padx=5, pady=5)
self.btn_close1=Button(self.frame_btn, text="Close", command=quit)
self.btn_close1.pack(side=LEFT, padx=5, pady=5)
# When tab focus is on the "Close" button, change Return behaviour.
self.btn_close1.bind("<Return>", lambda event: self.quit())
def main():
root = Tk()
root.geometry("300x250+300+200")
app = Example()
root.bind("<Return>", lambda event: app.convert())
root.mainloop()
if __name__ == '__main__':
main()
I have created a menu bar and a textbox, in the textbox I like to show the info in the variable that belongs to the chooice that been made in the menu.
But I can not figure out how.
Heres what I managed to put together by different guides on the web. Im verry new to python and Im still struggeling with the concept on objects and classes so any help at all will be greatly appriciated.
from tkinter import Tk, Frame, Menu
from tkinter import *
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("syntax explenation for shopfloor")
menubar = Menu(self.master)
self.master.config(menu=menubar)
syntaxMenu = Menu(menubar, tearoff=False)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Math', menu=submenu, underline=0)
submenu.add_command(label="abs()", command=self.onSyntaxabs)
submenu.add_command(label="cos()", command=self.onSyntaxcos)
submenu.add_command(label="sin()", command=self.onSyntaxsin)
submenu.add_cascade(label="log()", command=self.onSyntaxlog)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Inqurie', menu=submenu, underline=0)
submenu.add_command(label="inqiureText()", command=self.onSyntaxinquire)
menubar.add_cascade(label="Syntax", underline=0, menu=syntaxMenu)
def onSyntaxabs():
info="Convert to absolute value, abs(-10) will respond with 10."
def onSyntaxcos():
info="Returns cosinus value in decimal degrees"
def onSyntaxcos():
info="Returns cosinus value in decimal degrees"
def onSyntaxlog():
info="Returns the natural logarithm"
def onSyntaxinquire():
info="Creates a pop-up box that you can enter text in."
def main():
root = Tk()
root.geometry("500x600")
app = Example()
S = Scrollbar(root)
T = Text(root, height=20, width=60, bg="lightblue")
S.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=BOTH)
T.pack(side=RIGHT, fill=BOTH)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
info=?
T.insert(END, info)
mainloop( )
if __name__ == '__main__':
main()
Here's a little push forward:
from tkinter import Tk, Frame, Menu, Scrollbar, Text
from tkinter import RIGHT, LEFT, BOTH, END, Y
from tkinter import StringVar
class Example(Frame):
def __init__(self, master):
super().__init__(master)
self.pack(fill=BOTH, expand=True)
self.initUI()
def initUI(self):
self.master.title("syntax explenation for shopfloor")
menubar = Menu(self.master)
self.master.config(menu=menubar)
syntaxMenu = Menu(menubar, tearoff=False)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Math', menu=submenu, underline=0)
submenu.add_command(label="abs()", command=self.onSyntaxabs)
submenu.add_command(label="cos()", command=self.onSyntaxcos)
submenu.add_command(label="sin()", command=self.onSyntaxsin)
submenu.add_cascade(label="log()", command=self.onSyntaxlog)
submenu = Menu(syntaxMenu)
syntaxMenu.add_cascade(label='Inqurie', menu=submenu, underline=0)
submenu.add_command(label="inqiureText()", command=self.onSyntaxinquire)
menubar.add_cascade(label="Syntax", underline=0, menu=syntaxMenu)
S = Scrollbar(self) # Should probably be an instance member as well
self.text = Text(self, height=20, width=60, bg="lightblue")
S.pack(side=RIGHT, fill=Y)
self.text.pack(side=LEFT, fill=BOTH)
self.text.pack(side=RIGHT, fill=BOTH)
S.config(command=self.text.yview)
self.text.config(yscrollcommand=S.set)
self.setText("?")
def setText(self, text):
self.text.delete(1.0,END)
self.text.insert(END, text)
def onSyntaxabs(self):
self.setText("Convert to absolute value, abs(-10) will respond with 10.")
def onSyntaxsin(self):
self.setText("Returns sinus value in decimal degrees")
def onSyntaxcos(self):
self.setText("Returns cosinus value in decimal degrees")
def onSyntaxlog(self):
self.setText("Returns the natural logarithm")
def onSyntaxinquire(self):
self.setText("Creates a pop-up box that you can enter text in.")
def main():
root = Tk()
root.geometry("500x600")
app = Example(master=root)
app.mainloop()
if __name__ == '__main__':
main()
In general, I'd try to avoid importing all those symbols and just do something like
import tkinter as tk
then where you write Frame or RIGHT you'd use tk.Frame or tk.RIGHT.
Also, I moved all your widget creation inside of the class. So now your Text widget is a class member (self.text) and can be accessed and controlled easily from within the class -- all of your onSyntax___ methods call setText (another class method) which sets the Text widget's contents.
Hope it helps.
Thank you all for your input.
And I'll will continue to work with your post jedward.
I'll look in to Eclipse and Py Charm since I really need something like that.
How can I get a blocking modal input dialog box in standard Python?
I need the user to input a value before the code can proceed.
Here is some not-working test code, but the idea is that I should be able to call MyDialog from anywhere in the script, so this is just a simplified example.
import tkinter
class MyDialog:
def __init__(self, prompt):
self.top = tkinter.Toplevel()
tkinter.Label(self.top, text=prompt).pack()
self.e = tkinter.Entry(self.top)
self.e.pack(padx=5)
tkinter.Button(self.top, text="OK", command=self.ok).pack(pady=5)
def ok(self):
self.top.destroy()
return self.e.get()
root = tkinter.Tk()
userName = MyDialog('Enter your name')
tkinter.Label(root, text="Hello {}".format(userName)).pack()
root.mainloop()
The dialog should not only disable the master window, but block whatever code called it. And it should be able to pass the value back to the calling code.
The solution requires two critical pieces. First, use grab_set to block all events in the other window (or, more correctly, send all events to the dialog window). Second, use wait_window to prevent the method from returning until the dialog has been destroyed.
That being said, you shouldn't be using it like in your example. You need to have the mainloop running before you create the window. It might work OK on some platforms, but in general you shouldn't expect your GUI to behave properly until mainloop is running.
Here's a simple example:
import Tkinter as tk
class MyDialog(object):
def __init__(self, parent, prompt):
self.toplevel = tk.Toplevel(parent)
self.var = tk.StringVar()
label = tk.Label(self.toplevel, text=prompt)
entry = tk.Entry(self.toplevel, width=40, textvariable=self.var)
button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy)
label.pack(side="top", fill="x")
entry.pack(side="top", fill="x")
button.pack(side="bottom", anchor="e", padx=4, pady=4)
def show(self):
self.toplevel.grab_set()
self.toplevel.wait_window()
value = self.var.get()
return value
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.button = tk.Button(self, text="Click me!", command=self.on_click)
self.label = tk.Label(self, text="", width=40)
self.label.pack(side="top", fill="x")
self.button.pack(padx=20, pady=20)
def on_click(self):
result = MyDialog(self, "Enter your name:").show()
self.label.configure(text="your result: '%s'" % result)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
I'm trying to make my first GUI program. The problem is, that I can't figure out how to make a main menu, which would switch to one of the programs after clicking a button.
#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()
I know that I'm doing it wrong. I just have no idea how to do it, So i gave it a try of how could it be. Please help me.
You could call pack_forget() to hide widgets, and (later)
pack to show them again:
Tkinter is singled-threaded, and mainloop runs the main event loop. Therefore you shouldn't call mainloop twice.
#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()