I am trying to get the input of what page number the user wants. They should type in a number, and click the submit button. To test it, I just want to print whatever they typed and then close the window. I've been following: http://effbot.org/tkinterbook/entry.htm as a guide, but I am stumped.
Why does
print(temp)
not print out a number to console?
right now it prints out:
<bound method IntVar.get of <tkinter.IntVar object at 0x000001FBC85353C8>>
I've cleaned up the code a little bit:
import sys
from file import *
from page import *
from view import View
import tkinter as tk
from tkinter import *
class ViewGui:
def __init__(self):
#Included in the class, but unrelated to the question:
self._file = File("yankee.txt", 25)
self.pages = self._file.paginate()
self.initial_list = self.pages[0].readpage(self._file.fo)
self.initial_string = ''.join(self.initial_list)
# Create root
self.root = Tk()
self.root.wm_title("yankee.txt - page 1")
# Create frame for buttons
self.bframe = Frame(self.root)
self.bframe.pack(side=BOTTOM, fill=X)
self.tbutton = tk.Button(self.bframe, text="Top", command=lambda a="top": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.bbutton = tk.Button(self.bframe, text="Bottom", command=lambda a="bottom": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.ubutton = tk.Button(self.bframe, text="Up", command=lambda a="up": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.dbutton = tk.Button(self.bframe, text="Down", command=lambda a="down": self.clicks(a)).pack(side=LEFT, expand=1, fill=X)
self.pbutton = tk.Button(self.bframe, text="Page", command=lambda a="page": self.pageclicks()).pack(side=LEFT, expand=1, fill=X)
self.qbutton = tk.Button(self.bframe, text="Quit", command=quit).pack(side=LEFT, expand=1, fill=X)
# Create and pack Text
self.T = Text(self.root, height=35, width=60, wrap=NONE)
self.T.pack(side=TOP, fill=X)
# Create and pack Scrollbar
self.S = Scrollbar(self.root, orient=HORIZONTAL, command=self.T.xview)
self.S.pack(side=BOTTOM, fill=X)
# Attach Text to Scrollbar
self.T.insert('1.0', self.initial_string)
self.T.config(xscrollcommand=self.S.set, state=DISABLED)
self.S.config(command=self.T.xview)
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = Tk()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop.entrytext = IntVar()
Entry(pop, textvariable=pop.entrytext).pack()
pop.submitbuttontext = StringVar()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
pop.cancelbuttontext = StringVar()
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, a):
print('submitted is getting called')
temp = (a.entrytext.get)
print(temp)
def clicks(self, a):
print("you clicked clicks with the " + a)
self.root.wm_title(self._file.filename + " - Page " + self._file.buttonHandler(a))
if __name__ == "__main__":
vg = ViewGui()
vg.root.mainloop()
When you create a new window you should not use Tk(), you must use tk.Toplevel()
Must change:
pop = Tk()
to
pop = tk.Toplevel()
You should also use get(), not just get. Must change:
temp = (a.entrytext.get)
to
temp = a.entrytext.get()
Code:
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = tk.Toplevel()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop.entrytext = IntVar()
Entry(pop, textvariable=pop.entrytext).pack()
pop.submitbuttontext = StringVar()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
pop.cancelbuttontext = StringVar()
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, a):
print('submitted is getting called')
temp = a.entrytext.get()
print(temp)
Made changes to these two methods and now it is working.
def pageclicks(self):
print("pageClicks is getting called at least...")
pop = Tk()
pop.wm_title("Page Number")
pop.label = Label(pop, text="Enter a Page Number:", width=35)
pop.label.pack(side=TOP)
pop._entry = Entry(pop)
pop._entry.pack()
pop._entry.focus_set()
Button(pop, text="Submit", command=lambda a=pop: self.submitted(a)).pack(side=LEFT, pady=5, padx=40)
Button(pop, text="Cancel", command=pop.destroy).pack(side=LEFT, pady=5, padx=40)
def submitted(self, _pop):
temp = _pop._entry.get()
print(temp)
_pop.destroy()
Related
class Menu():
def __init__(self):
pass
def menuWindow(self):
menu = Tk()
menu.title("Menu")
menu.geometry("300x250")
menuFrame = Frame(menu)
menuFrame.pack()
menu = Menu()
menuLabel = Label(menuFrame, font="Helvetica 18 bold", text="MENU")
menuLabel.grid(row=0, column=0, sticky=W)
cDirF = TaskWindowMaker()
cDir = Button(menuFrame, text="Create Directory", command=cDirF.cDirWindow, height=2,width=20)
cDir.grid(row=2, column=0, sticky=W)
cProfF = TaskWindowMaker()
cProf = Button(menuFrame, text="Create Profiles", command=cProfF.cProfWindow, height=2,width=20)
cProf.grid(row=3, column=0, sticky=W)
dProfF = TaskWindowMaker()
dProf = Button(menuFrame, text="Delete Profiles", command=dProfF.dProfWindow, height=2,width=20)
dProf.grid(row=6, column=0, sticky=W)
mSenderF = TaskWindowMaker()
mSender = Button(menuFrame, text="Make Sender", command=mSenderF.mSenderWindow, height=2,width=20)
mSender.grid(row=8, column=0, sticky=W)
sendParcelF = TaskWindowMaker()
sParcel = Button(menuFrame, text="Send Parcel", command=sendParcelF.sendParcelWindow, height=2,width=20)
sParcel.grid(row=10, column=0, sticky=W)
class ProfileDeveloper(object):
def __init__(self,):
pass
def create_folder_profiles(self):
global directoryNamecProfWindow
y = False
while y == False:
path = os.getcwd()
print(path)
y = numbercProfWindow.get()#int(input("Number of profiles: "))
print(y)
#y = int(y)
p = os.getcwd()+("\profiles")#Reading number file in profiles
n = ("number")
d = os.path.join(p,n)
try:
dirName = directoryNamecProfWindow.get()#input("Directory name :")
print(dirName+"OO")
path = os.getcwd()+("\profiles")
folderDir = os.path.join(path, dirName)
with open(folderDir+"profile.txt","x") as f:
print("Opened.")
except FileNotFoundError:
print("File not found.")
except FileExistsError:
messagebox.showerror("Error","File already exists.")
for a in range(y):
with open(d+".txt","r") as z:
num = z.read()
num = int(num)
newNum = (int(num)+1)
numProf = ("profile"+str(newNum))
with open(d+".txt","w") as file:
file.write(str(newNum))
path = os.getcwd()+("\profiles")
folderDir = os.path.join(path, dirName,numProf)
with open(folderDir+".txt","x") as f:
print("Created '"+numProf+"'.")
y = True
#except:
print("Saved to "+folderDir+"\n")
class TaskWindowMaker(object):
def __init__(self):
pass
def cProfWindow(self):
global numbercProfWindow
cProf = Tk()
cProf.title("Create Profiles")
cProf.geometry("300x250")
cProfFrame = Frame(cProf)
cProfFrame.pack()
titleLabel = Label(cProfFrame, font="Helvetica 18 bold", text="Create Profiles")
titleLabel.grid(row=0, column=0, sticky=W)
menuLabel = Label(cProfFrame, text="Folder Name")
menuLabel.grid(row=1, column=0, sticky=W)
directoryNamecProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=directoryNamecProfWindow)
cDirEntry.grid(row=1, column=1, sticky=W)
menuLabel = Label(cProfFrame, text="Number of Profiles")
menuLabel.grid(row=2, column=0, sticky=W)
numbercProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=numbercProfWindow)
cDirEntry.grid(row=2, column=1, sticky=W)
cProfF = ProfileDeveloper(directoryNamecProfWindow)
cDir = Button(cProfFrame, text="Enter", command=cProfF.create_folder_profiles, height=2,width=20)
cDir.grid(row=3, column=0, sticky=W)
start = Menu()
start.menuWindow()
This is my code. I'm opening multiple Windows. Then when I enter in an input box in
numbercProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=numbercProfWindow)
cDirEntry.grid(row=2, column=1, sticky=W)
I'm then using the button:
cProfF = ProfileDeveloper(directoryNamecProfWindow)
cProf = Button(cProfFrame, text="Enter", command=cProfF.create_folder_profiles, height=2,width=20)
cProf.grid(row=3, column=0, sticky=W)
To send the input to ProfileDeveloper.create_folder_profiles
When it's sent to ProfileDeveloper.create_folder_profiles the program doesn't recognise the input, as in it's not '.get()ing it'.
I'm quite new so don't know how to pass variables between different functions and using the .get() function or global variables.
The main aim of the program is creating a profiles (txt files) in a specified folder. Instead of it being a script in shell I'm trying to add a Tkinter GUI.
Hopefully this explains it as I've asked before and people just get too confused. There's still a lot of code which I don't show but the confusion between passing variables continues throughout the code so not sure. The code was really long and just running in Shell then I added the Tkinter GUI and it's complicated it all by doubling variables and now this, so any help is greatly appreciated.
Thanks :)
Does this example help You understand better what You can do:
from tkinter import Tk, Entry, Button
root = Tk()
class UserInput:
def __init__(self, master):
self.master = master
self.entry = Entry(self.master)
self.entry.pack()
self.button = Button(self.master, text='Submit', command=self.submit)
self.button.pack()
def submit(self):
entry_var = self.entry.get()
print(entry_var)
user_input = UserInput(root)
root.mainloop()
I'm trying to get the value of the radiobutton selcted and storing this int into a varable. It's my first tkinter project, so I'm sorry for my probably stupid mistakes...
from tkinter import *
from tkinter import ttk
select = "A"
def begin():
grand = Tk()
grand.title("Converter")
window.destroy()
frame = Frame(grand)
option = IntVar()
-> AttributeError: 'NoneType' object has no attribute '_root'
grandlabel = Label(frame, text="Choose the grand").grid(row=0, sticky=N, padx=5)
grand1 = Radiobutton(frame, text="Speed", variable=option, value=1, command=sel).grid(row=1, sticky=W)
grand2 = Radiobutton(frame, text="etc", variable=option, value=2, command=sel).grid(row=2, sticky=W)
submitgrand = Button(frame, text="Ok", command=unit).grid(row=3, sticky=W)
frame.pack()
grand.mainloop()
def sel():
global option
global select
select = option.get()
option = StringVar()
def unit():
unit = Tk()
global select
select = grandchosen
if (grandchosen == "Speed"):
Label(unit, text="Test").pack()
else:
Label(unit, text="Test2").pack()
unit.mainloop()
root = Tk()
frame = Frame(root)
welcome = ttk.Label(frame, text="Welcome!").grid(row=0, sticky=N, padx=10, pady=3)
okbutton = Button(frame, text="Ok", width=15, command=begin).grid(row=1, sticky=S, padx=20, pady=30)
frame.pack()
style = ttk.Style()
style.configure("TLabel", foreground="midnight blue", font="Times 19")
root.mainloop()
Would be great to get some help, thank you!
I'm trying to build youtube downloader application with GUI using python3.
After learning basics of python I'm trying to build one. I'm using "pafy" and "TKinter" modules.
Following are the widgets involved in the GUI
1. One Entry field to input the URL
2. Next to it paste button
3. A media select drop down menu
4. One more drop down menu to list the media quality(depends on previous media input)
5. Finally a download button
Here is my code
from tkinter import *
from tkinter import ttk
import pafy
master = Tk()
media_option = StringVar()
audio_quality_lsit = []
audio_quality_drop_menu = StringVar()
video_quality_lsit = []
video_quality_drop_menu = StringVar()
def url():
global data
url = url_field.get()
data = pafy.new(url)
def audio():
global selected_audio
audio_streams = data.audiostreams
for audio_quality in audio_streams:
audio_quality_lsit.append(audio_quality.bitrate)
selected_audio = audio_quality_drop_menu.get()
print("selected_audio") #Debug Statement
Label(master, text="Audio Bitrate: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(master, audio_quality_drop_menu, *audio_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def video():
global selected_video
video_streams = data.streams
for video_quality in video_streams:
video_quality_lsit.append(video_quality.resolution)
selected_video = video_quality_drop_menu.get()
print("selected_video") #Debug Statement
Label(master, text="Video Quality: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(master, video_quality_drop_menu, *video_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def media_select(self):
global A_V
A_V = media_option.get()
if A_V == "Audio":
audio()
elif A_V == "Video":
video()
def download():
if selected_audio:
print("Audio") #Debug Statement
selected_audio.download(quiet=False)
elif selected_video:
print("Video") #Debug Statement
selected_video.download(quiet=False)
Label(master, text="YouTube URL:").grid(row=0)
url_field = Entry(master)
url_field.grid(row=0, column=1)
Button(master, text='Paste URL', command=url).grid(row=0, column=4, sticky=W, pady=10)
Button(master, text='Download', command=download).grid(row=12, column=4, sticky=W, pady=10)
Label(master, text="Media Type: ").grid(row=3)
media_drop_menu = OptionMenu(master, media_option, "Audio", "Video", command=media_select)
media_drop_menu.grid(row=5, column=0)
mainloop()
I'm stuck at "download function". Am I using the function properly?
Is there any problem in calling the function?
And one more thing, Sorry if it is dump question.
Why we have to do this,
from tkinter import *
from tkinter import ttk
According to my understanding when we use "*", will import all the modules present in the library. Again why we have to use "from tkinter import ttk".
Please help me.
UPDATE:
#JoshuaNixon Thanks for the replay.
I didn't know much about "classes" So first I learnt basics of it and I made some changes.
Here is the code:
from tkinter import *
import pafy
class YouTubeDownloader:
def __init__(self,master):
self.master = master
master.title("Youtube Downloader")
self.media_option = StringVar()
self.audio_quality_lsit = []
self.audio_quality_drop_menu = StringVar()
self.video_quality_lsit = []
self.video_quality_drop_menu = StringVar()
Label(master, text="YouTube URL:").grid(row=0)
self.url_field = Entry(master)
self.url_field.grid(row=0, column=1)
Button(master, text='Paste URL', command=self.url).grid(row=0, column=4, sticky=W, pady=10)
Button(master, text='Download', command=self.download).grid(row=12, column=4, sticky=W, pady=10)
Label(master, text="Media Type: ").grid(row=3)
media_drop_menu = OptionMenu(master, self.media_option, "Audio", "Video", command=self.media_select)
media_drop_menu.grid(row=5, column=0)
def url(self):
global data
url = self.url_field.get()
data = pafy.new(url)
def media_select(self):
global A_V
A_V = self.media_option.get()
if A_V == "Audio":
audio()
elif A_V == "Video":
video()
def audio():
global selected_audio
audio_streams = self.data.audiostreams
for audio_quality in audio_streams:
audio_quality_lsit.append(audio_quality.bitrate)
selected_audio = audio_quality_drop_menu.get()
print("selected_audio") #Debug Statement
Label(master, text="Audio Bitrate: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(master, audio_quality_drop_menu, *audio_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def video(self):
global selected_video
video_streams = self.data.streams
for video_quality in video_streams:
video_quality_lsit.append(video_quality.resolution)
selected_video = video_quality_drop_menu.get()
print("selected_video") #Debug Statement
Label(master, text="Video Quality: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(master, video_quality_drop_menu, *video_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def download(self):
if selected_audio:
print("Audio") #Debug Statement
self.selected_audio.download(quiet=False)
elif selected_video:
print("Video") #Debug Statement
self.selected_video.download(quiet=False)
root = Tk()
my_youtube = YouTubeDownloader(root)
root.mainloop()
When I run the code, I get the GUI. After copy pasting URL field, I get error at "media_select()" saying that
"TypeError: media_select() takes 1 positional argument but 2 were given".
You suggested to make use of two classes. As I'm still beginner in this, I got little confused in the "self" argument. So I used single class.
Can you please tell me where I'm going wrong.
Thank You.
All the syntax errors have been solved. Only one exception is left that I think you can solve.
When you use a class use self.* for referring,
from Tkinter import *
import pafy
class YouTubeDownloader:
def __init__(self,master):
self.master = master
master.title("Youtube Downloader")
self.media_option = StringVar()
self.audio_quality_lsit = []
self.audio_quality_drop_menu = StringVar()
self.video_quality_lsit = []
self.video_quality_drop_menu = StringVar()
Label(master, text="YouTube URL:").grid(row=0)
self.url_field = Entry(master)
self.url_field.grid(row=0, column=1)
Button(master, text='Paste URL', command=self.url).grid(row=0, column=4, sticky=W, pady=10)
Button(master, text='Download', command=self.download).grid(row=12, column=4, sticky=W, pady=10)
Label(master, text="Media Type: ").grid(row=3)
media_drop_menu = OptionMenu(master, self.media_option, "Audio", "Video", command=self.media_select)
media_drop_menu.grid(row=5, column=0)
self.data = []
def url(self):
global data
url = self.url_field.get()
self.data = pafy.new(url)
def media_select(self, a):
global A_V
A_V = self.media_option.get()
if A_V == "Audio":
# for functions of same class use self.function()
self.audio()
elif A_V == "Video":
self.video()
def audio(self):
global selected_audio
audio_streams = self.data.audiostreams
for audio_quality in audio_streams:
self.audio_quality_lsit.append(audio_quality.bitrate)
selected_audio = self.audio_quality_drop_menu.get()
print("selected_audio") #Debug Statement
Label(self.master, text="Audio Bitrate: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(self.master, self.audio_quality_drop_menu, *self.audio_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def video(self):
global selected_video
video_streams = self.data.streams
for video_quality in video_streams:
self.video_quality_lsit.append(video_quality.resolution)
selected_video = self.video_quality_drop_menu.get()
print("selected_video") #Debug Statement
Label(self.master, text="Video Quality: ").grid(row=7, column=1)
show_drop_menu = OptionMenu(self.master, self.video_quality_drop_menu, *self.video_quality_lsit)
show_drop_menu.grid(row=9, column=1)
def download(self):
if selected_audio:
print("Audio") #Debug Statement
self.selected_audio.download(quiet=False)
elif selected_video:
print("Video") #Debug Statement
self.selected_video.download(quiet=False)
root = Tk()
my_youtube = YouTubeDownloader(root)
root.mainloop()
I'm new im Python, just started to learn about class and tkinter, so forgive me "messy" code.
I'm trying to enter some string to field nr1, and after click a button, print this string in console and store this value for later:
from tkinter import Tk, BOTH, RIGHT, RAISED, BOTTOM, TOP, X, StringVar
from tkinter.ttk import Frame, Button, Entry
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
global inp
a = self.raw_input(self.v.get())
inp = a
return inp
def initUI(self):
self.pack(fill=BOTH, expand=True)
frame = Frame(self, relief=RAISED, borderwidth=0)
frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
rename_button = Button(frame, text="Dispaly text", command = self.user_input())
rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
entry2 = Entry(frame)
entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
quit_button = Button(self, text="Quit", command=self.quit)
quit_button.pack(side=RIGHT, padx=5, pady=5)
ok_button = Button(self, text="OK")
ok_button.pack(side=RIGHT, padx=5, pady=5)
def main():
root = Tk()
app = AD(root)
root.mainloop()
if __name__ == '__main__':
main()
After executing code, i get:
TypeError: 'NoneType' object is not callable
Any help would me appreciated
ISSUES:
First issue laid in your rename_button's option "command=self.user_input()". You were suppose to name the function
and not execute the function. Putting the () symbol meant you
executed the function when your code loaded, i.e. it executed once
w/o pressing the rename button.
Second issue was the erroneous code in your function user_input. This caused your error msg.
ANSWER: Code with the suggested corrections.
from tkinter import *
from tkinter.ttk import *
class AD(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, v=None, raw_input=None)
self.parent = parent
self.parent.geometry("250x150+300+300")
self.parent.title("Trolollo")
self.parent.resizable(False, False)
self.inp = None
self.v = StringVar()
self.raw_input = None
self.initUI()
def user_input(self):
# Get entry1 value, store it as an attribute and print to console
self.raw_input = self.v.get()
print(self.raw_input)
def initUI(self):
self.frame = Frame(self, relief=RAISED, borderwidth=0)
self.frame.pack(fill=BOTH, expand=True)
self.entry1 = Entry(self.frame, textvariable=self.v)
self.entry1.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.entry1.focus_set()
#self.rename_button = Button(self.frame, text="Dispaly text",
# command = self.user_input())
self.rename_button = Button(self.frame, text="Display text",
command = self.user_input)
self.rename_button.pack(side=TOP, expand=False, padx=2, pady=2)
# You can remove the triple quotes to display these widgets
"""
self.entry2 = Entry(self.frame)
self.entry2.pack(side=TOP, fill=X, expand=False, padx=2, pady=2)
self.quit_button = Button(self.frame, text="Quit", command=self.quit)
self.quit_button.pack(side=RIGHT, padx=5, pady=5)
self.ok_button = Button(self.frame, text="OK")
self.ok_button.pack(side=RIGHT, padx=5, pady=5)
"""
self.pack(fill=BOTH, expand=True)
def main():
root = Tk()
app = AD(root)
root.mainloop()
Your GUI :
SUGGESTIONS:
Do remember to put self. in front of your widgets.
Do test one widget at a time to help you debug your code.
How do you check if the user has selected "Other" from the hopOptions selection, and then enable otherEntry if they did? And then disable it again if they select one of the other options.
class Interface():
def __init__(self, window):
frame = Frame(window)
frame.pack()
self.hopLabel = Label(frame, text="Hop:", anchor=E)
self.hopLabel.grid(row=0, column=0, sticky=EW)
hops = range(0,6)
hops.append("Other")
self.selectedHop = StringVar(frame)
self.selectedHop.set(hops[0])
self.hopOptions = OptionMenu(frame, self.selectedHop, *hops)
self.hopOptions.grid(row=0, column=2, sticky=EW)
self.otherEntry = Entry(frame, state=DISABLED)
self.otherEntry.grid(row=0, column=1, sticky=EW)
root = Tk()
app = Interface(root)
root.mainloop()
Bind the option menu to a command and add another method to your class. The command will run the class method with the value as an argument anytime an option is changed in the menu. There you can do validation to update the otherEntry widget. Also I would advise not doing from Tkinter import * as it appears that's what you've done. Generally importing an entire package could have conflicts with your namespace. This should suit your needs:
from Tkinter import *
class Interface():
def __init__(self, window):
frame = Frame(window)
frame.pack()
self.hopLabel = Label(frame, text="Hop:", anchor=E)
self.hopLabel.grid(row=0, column=0, sticky=EW)
hops = range(0,6)
hops.append("Other")
self.selectedHop = StringVar(frame)
self.selectedHop.set(hops[0])
self.hopOptions = OptionMenu(frame, self.selectedHop, *hops, command=self.optupdate)
self.hopOptions.grid(row=0, column=2, sticky=EW)
self.otherEntry = Entry(frame, state=DISABLED)
self.otherEntry.grid(row=0, column=1, sticky=EW)
def optupdate(self, value):
if value == "Other":
self.otherEntry.config(state=NORMAL)
else:
self.otherEntry.config(state=DISABLED)
if __name__ == "__main__":
root = Tk()
app = Interface(root)
root.mainloop()
As an alternative to iChar's command approach, Use selectedHop.trace to register a function that will be called whenever the selected item changes.
from Tkinter import *
class Interface():
def __init__(self, window):
frame = Frame(window)
frame.pack()
self.hopLabel = Label(frame, text="Hop:", anchor=E)
self.hopLabel.grid(row=0, column=0, sticky=EW)
hops = range(0,6)
hops.append("Other")
self.selectedHop = StringVar(frame)
self.selectedHop.set(hops[0])
self.selectedHop.trace("w", self.selected_hop_changed)
self.hopOptions = OptionMenu(frame, self.selectedHop, *hops)
self.hopOptions.grid(row=0, column=2, sticky=EW)
self.otherEntry = Entry(frame, state=DISABLED)
self.otherEntry.grid(row=0, column=1, sticky=EW)
def selected_hop_changed(self, *args):
value = self.selectedHop.get()
if value == "Other":
self.otherEntry.config(state=NORMAL)
else:
self.otherEntry.config(state=DISABLED)
root = Tk()
app = Interface(root)
root.mainloop()