1

The title is not very easy to understand, I know, so let me explain it here.

Basically if I do

if variable.get() == "Select Website":
    print("ok")

it will print out "ok", but if I change it from "Select Website" to "Fareham" as well as the option in the drop down box to "Fareham" it will not notice it changed. If I want it to notice it changed I would need to do a while loop, but that would stop the script running in the first place.

How can I make the script print out "ok" if variable is changed to "Fareham"?

Current Code:

import tkinter

sites = [
    "Fareham",
    "Hants",
    "Southampton",
    "Eastleigh",
    "Havant",
    "Gosport",
]

win = tkinter.Tk()

win.geometry("500x500")

variable = tkinter.StringVar(win)
variable.set("Select Website")

drop = tkinter.OptionMenu(win, variable, *sites)
drop.pack()

if variable.get() == "Fareham":
    print("ok")

win.mainloop()

2 Answers2

0

Here's where some important info can be found: http://effbot.org/tkinterbook/variable.htm

By setting an observer to the variable variable, it will check it everytime it changes.

def check(*args):
    if variable.get() == 'Fareham':
        print 'ok'

variable.trace(
    'w',    # 'w' checks when a variable is written (aka changed)
    check   # this is the function it should call when the variable is changed
)

Just put the code in place of your current if statement and it will work like a charm.

GeeTransit
  • 1,458
  • 9
  • 22
0

You can do this by associating a callback funtion to the drop down menu:

import tkinter

def your_callback(*args):

    if args[0] == "Fareham":
        print("ok")

sites = [
    "Fareham",
    "Hants",
    "Southampton",
    "Eastleigh",
    "Havant",
    "Gosport",
]

win = tkinter.Tk()

win.geometry("500x500")

variable = tkinter.StringVar(win)
variable.set("Select Website")



drop = tkinter.OptionMenu(win, variable, *sites, command = your_callback)
drop.pack()



win.mainloop()
Hemerson Tacon
  • 2,419
  • 1
  • 16
  • 28
  • How could I remove the text box when the choice is changed to something that is not "Fareham"? – Zeref Dragneel Nov 12 '18 at 14:44
  • Just execute the opposite check (`if not args[0] == "Fareham":`) and then execute the command to remove the text box – Hemerson Tacon Nov 12 '18 at 14:54
  • There are already a question which answers this: [How to clear/delete the contents of a Tkinter Text widget?](https://stackoverflow.com/questions/27966626/how-to-clear-delete-the-contents-of-a-tkinter-text-widget). If this doesn't give any clarification to you, I suggest that you post another question since this discussion is gettting out of this current question's scope. – Hemerson Tacon Nov 13 '18 at 14:40