There are several things preventing the code in your question from working.
The NameError
is occurring because the global variable Country
doesn't exist when the print(Country)
call is executed. That can be fixed by simply defining the variable beforehand—probably somewhere near the beginning of the script.
Somewhat related to that issue, is the fact that in the CountryChoice()
function, Country
is considered a local variable, so setting its value there doesn't affect the global variable with the same name. That can be fixed by declaring the variable to be global
at the beginning of the function.
Lastly, when using Radiobutton
widgets, the type of value
option should match the type of tkinter variable being used. In this case, the values are integers, so I changed the variable type of observer
from tk.StringVar
to tk.IntVar
.
I've made those changes and added a call to a treatment()
function to the end of the CountryChoice()
function to print the current value everytime it's called.
#coding:utf-8
import tkinter as tk
app = tk.Tk()
Country = None # Declare global variable.
def CountryChoice(*args):
global Country
if observer.get() == 0:
Country = "France"
elif observer.get() == 1:
Country = "United Kingdom"
treatment() # Use current value of Country.
observer = tk.IntVar() # Use IntVar since Radiobutton values are integers.
observer.trace("w", CountryChoice)
FranceRadio = tk.Radiobutton(app, text="France", variable=observer, value=0)
UKRadio = tk.Radiobutton(app, text="UK", variable=observer, value=1)
FranceRadio.grid(row=0, column=0)
UKRadio.grid(row=0, column=1)
def treatment():
# Reuse the variable Country.
print(Country)
app.mainloop()
In closing, I'd like to make a few suggestions.I strongly suggest that you read and start following the PEP 8 - Style Guide for Python Code recommendations, particularity the sections about Naming Conventions and Code Layout. This will make your code easier to work on and maintain—as well as easier for others to read.
Likewise, the accepted answer to the question Best way to structure a tkinter application? has some excellent suggestions from a tkinter expert on the best way to structure tkinter applications that would, if you followed them, eliminate the need to use most global variables (which are considered by many to be a poor programming practice).