I am teaching a class and have been told to avoid global statements using Python and Tkinter. I don't want to teach Classes to my students yet
I know I can create all my entry boxes and labels out of a subroutine and my code will work, but this is just teaching a different bad practice
from tkinter import *
def print_name():
print(entry_location.get())
def main():
global main_window,entry_location
main_window =Tk()
Button(main_window, text="Print Name",command=print_name) .pack()
entry_location = Entry(main_window)
entry_location.pack()
main_window.mainloop()
main()
This works with the global statement, but short of removing the code in main() from the subroutine is there an alternative?
In your example, you can eliminate globals by registering a lambda function to the button; this lambda function collects te value in the entry, and passes it as a parameter to print_name
.
import tkinter as tk
def print_name(text=''): # <- now receives a value as parameter
print(text)
def main():
main_window = tk.Tk()
entry_location = tk.Entry(main_window)
tk.Button(main_window, text="Print Name", command=lambda: print_name(entry_location.get())).pack()
entry_location.pack()
main_window.mainloop()
main()
This answers the special case of your example; it is not a generic answer to eliminating globals entirely. Alternative approaches could be to place the variables needed globally in a dictionary, or a list, thus permitting their modification in the local spaces, but in the end, it might become more complicated than using a proper class.
As suggested by @AndrasDeak, it is better to avoid star imports.
as phydeaux said, you can do this py simply passing the variables as parameters.
full ammended code shown below:
from tkinter import *
def print_name(entry_location):
print(entry_location.get())
def main(main_window, entry_location):
main_window =Tk()
Button(main_window, text="Print Name",command=print_name) .pack()
entry_location = Entry(main_window)
entry_location.pack()
main_window.mainloop()
main(main_window, entry_location)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.