Tkinter background colour issue - python

I have a script that has a Tkinter module in it that i would like to change the background color in 3min intervals e.g green for 3mins then orange then red.
I have the code to display the green but can't get it to change.
When I make a function in my code it gets a few different errors including
'root not defined, global name "root" no defined' although it is.
Also on a side note kill the Tk display after 15 mins so once all 3 colours have been though.
from __future__ import absolute_import
from . import BasePlugin
import os, sys
import time
from Tkinter import *
def Orange (*args,**kwargs):
root.config(background="Orange")
def Red(*args,**kwargs):
root.config(background="Red")
class dis(BasePlugin):
def execute(self, msg, unit, address, when, printer, print_copies):
mseg = str('%s - %s' % (msg, unit))
root = Tk()
root.title('label')
txt = Label(root, font= 'times 20 bold', bg='Green')
txt.config(text= mseg)
txt.pack(fill=BOTH, expand=0)
root.after(10,Orange)
root.after(10,Red)
root.mainloop(0)
PLUGIN = dis
I have also tried
from __future__ import absolute_import
from . import BasePlugin
import os, sys
import time
from Tkinter import *
def Orange (*args,**kwargs):
txt.config(background="Orange")
def Red(*args,**kwargs):
txt.config(background="Red")
class dis(BasePlugin):
def execute(self, msg, unit, address, when, printer, print_copies):
mseg = str('%s - %s' % (msg, unit))
root = Tk()
root.title('label')
txt = Label(root, font= 'times 20 bold', bg='Green')
txt.config(text= mseg)
txt.pack(fill=BOTH, expand=0)
txt.after(10,Orange)
txt.after(10,Red)
root.mainloop(0)
PLUGIN = dis
If I place root = Tk() anywhere else I get a small gray TK box that I don't want.
P.S I know that it's set to 10 seconds that's only so I can test it

There are (at least) four problems with your code, but that's difficult to tell, since you are not showing us all the details. In particular, you never seem to call execute, but I'll assume that this happens somewhere else, maybe via the super class...
root is defined inside execute, thus to access it in your callback functions, you either have to make it global, or a member of the dis instance, or put the callback functions inside execute
the delay in after is in milliseconds, so using 10 the colours will switch instantaneously, which is probably not the best setup for testing
as it stands, both after callbacks are executed at the exact same time; either put one at the end of the other callback function, or use different times
you change the background of the root panel, while in fact you want to change the background of the txt Label
For example, you could try like this (minimal stand-alone example)
class dis:
def execute(self):
def orange():
txt.config(bg="Orange")
root.after(2000, red)
def red():
txt.config(bg="Red")
root.after(2000, kill)
def kill():
root.destroy()
root = Tk()
txt = Label(root, text="some text", font='times 20 bold', bg='Green')
txt.pack(fill=BOTH, expand=0)
root.after(2000, orange)
root.mainloop()
dis().execute()
Or shorter, just using a bunch of lambda:
class dis:
def execute(self):
root = Tk()
txt = Label(root, text="some text", font='times 20 bold', bg='Green')
txt.pack(fill=BOTH, expand=0)
root.after(2000, lambda: txt.config(bg="Orange"))
root.after(4000, lambda: txt.config(bg="Red"))
root.after(6000, root.destroy)
root.mainloop()
dis().execute()

Or a little more generic using a list
class dis():
def __init__(self):
mseg = ("test message")
self.color_list=["green", "orange", "red"]
self.ctr=0
root = Tk()
root.title('label')
self.txt = Label(root, font= 'times 20 bold', width=20)
self.txt.config(text= mseg)
self.txt.pack(fill=BOTH, expand=0)
self.change_color()
root.mainloop()
def change_color(self):
self.txt.config(background=self.color_list[self.ctr])
self.ctr += 1
if self.ctr > 2:
self.ctr=0
self.txt.after(500, self.change_color)
PLUGIN = dis()

Related

tkinter code after mainloop() not being executed after closing window

I need help using tkinter in python.
I want to use a while loop inside my class so that it keeps printing in the terminal the content of an entry (box1). But the problem is that if I put a loop in my class the entry wont even be created because the root.mainloop() is after my while loop.
The program:
from tkinter import *
from tkinter import ttk
import tkinter as tk
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.minsize(500,400)
self.configure(bg='#121213')
self.createEntry()
def createEntry(self):
self.name1 = StringVar()
self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
self.box1.place(x=128, y=31)
while True:
print(self.name1.get())
root=root()
root.mainloop()
If I put the loop after the root.mainloop() it won't start printing the contents of name1 as long as the tkinter file is open. So it will print only the final version of name1 in a loop:
The Code:
from tkinter import *
from tkinter import ttk
import tkinter as tk
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.minsize(500,400)
self.configure(bg='#121213')
self.createEntry()
def createEntry(self):
self.name1 = StringVar()
self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
self.box1.place(x=128, y=31)
while True:
print(self.name1.get())
root=root()
root.mainloop()
while True:
print(root.name1.get())
Video of my problem
Does anyone have any solution?
How about a solution that does not put constant drain on the processing power?
If you add a callback to StringVar, you can trigger a function every time the variable is changed, and only then. Infinite loops don't work very well with UI applications, as in order to avoid stopping the control flow of the app you have to use things like async, threading etc.
def createEntry(self):
self.name1 = StringVar()
self.name1.trace_add("write", lambda name, index, mode: print(self.name1.get()))
self.box1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15")
self.box1.place(x=128, y=31)
This piece of code will make given lambda function trigger every time something is written to name1 variable.

Tkinter module - program will just run then stop and won't open the window

I need help, I am doing a budget calculator and using tkinter for the first time and wondered why it is not working...
When I run it, it will just end straight away and when I put the root = Tk() at the end it comes up with an error.
I really need help, my code is below...
from time import sleep
from tkinter import *
from tkinter import messagebox, ttk, Tk
root = Tk()
class GUI():
def taskbar(self):
menu = Menu()
file = Menu(menu)
file.add_command(label="Exit", command=self.exit_GUI)
file.add_command(label = "Information", command=self.info_popup)
def Main_Menu(self):
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
Income_button = Button(topFrame, text="Enter your incomes", command=self.Income)
Expense_button = Button(topFrame, text="Enter your expenses", command=self.Expense)
Total_button = Button(bottomFrame, text="View Results", command=self.Total)
Income_button.pack()
Expense_button.pack()
Total_button.pack()
def Income(self):
pass
def Expense(self):
pass
def Total(self):
pass
def exit_GUI(self):
exit()
def info_popup():
pass
g = GUI()
g.Main_Menu()
g.taskbar()
g.Income()
g.Expense()
g.Total()
g.exit_GUI()
g.info_popup()
root.mainloop()
You are exiting before you ever get to the mainloop with:
g.exit_GUI()
That method is calling the standard exit() and stopping the entire script. Remove or comment out the above call. You will also need to add self as an argument to info_popup to get your script to run:
def info_popup(self):
pass

Getting variable out of Tkinter

I would like to ask if anyone knows how to get out a variable from an Entry in Tkinter to be used in future calculation.
Let us assume that I want to create a prompt where the user needs to place two numbers in the two different Entry widgets.
These numbers are to be used in another script for calculation. How can I retrieve the values from the prompt created in Tkinter?
In my opinion, I would need to create a function with the code bellow and make it return the value from the Tkinter prompt. However, I cannot return the numbers because I'm destroying the root window. How can I get pass this, preferably without global variables.
Best Regards
from tkinter import *
from tkinter import ttk
#Start of window
root=Tk()
#title of the window
root.title('Title of the window')
def get_values():
values=[(),(value2.get())]
return values
# Creates a main frame on the window with the master being the root window
mainframe=ttk.Frame(root, width=500, height=300,borderwidth=5, relief="sunken")
mainframe.grid(sticky=(N, S, E, W))
###############################################################################
#
#
# Label of the first value
label1=ttk.Label(master=mainframe, text='First Value')
label1.grid(column=0,row=0)
# Label of the second value
label2=ttk.Label(master=mainframe, text='Second Value')
label2.grid(column=0,row=1)
###############################################################################
#
#
# Entry of the first value
strvar1 = StringVar()
value1 = ttk.Entry(mainframe, textvariable=strvar1)
value1.grid(column=1,row=0)
# Entry of the second value
strvar2 = StringVar()
value2 = ttk.Entry(mainframe, textvariable=strvar2)
value2.grid(column=1,row=1)
# Creates a simplle button widget on the mainframe
button1 = ttk.Button(mainframe, text='Collect', command=get_values)
button1.grid(column=2,row=1)
# Creates a simplle button widget on the mainframe
button2 = ttk.Button(mainframe, text='Exit', command=root.destroy)
button2.grid(column=2,row=2)
root.mainloop()
You use a class because the class instance and it's variables remain after tkinter exits.https://www.tutorialspoint.com/python/python_classes_objects.htm And you may want to reexamine some of your documentation requirements, i.e. when the statement is
"root.title('Title of the window')", adding the explanation "#title of the window" is just a waste of your time..
""" A simplified example
"""
import sys
if 3 == sys.version_info[0]: ## 3.X is default if dual system
import tkinter as tk ## Python 3.x
else:
import Tkinter as tk ## Python 2.x
class GetEntry():
def __init__(self, master):
self.master=master
self.entry_contents=None
self.e = tk.Entry(master)
self.e.grid(row=0, column=0)
self.e.focus_set()
tk.Button(master, text="get", width=10, bg="yellow",
command=self.callback).grid(row=10, column=0)
def callback(self):
""" get the contents of the Entry and exit
"""
self.entry_contents=self.e.get()
self.master.quit()
master = tk.Tk()
GE=GetEntry(master)
master.mainloop()
print("\n***** after tkinter exits, entered =", GE.entry_contents)
So, I have taken Curly Joe's example and made a function with the his sketch
The final result, for anyone wanting to use this as a template for a input dialog box:
def input_dlg():
import tkinter as tk
from tkinter import ttk
class GetEntry():
def __init__(self, master):
self.master=master
self.master.title('Input Dialog Box')
self.entry_contents=None
## Set point entries
# First point
self.point1 = ttk.Entry(master)
self.point1.grid(row=0, column=1)
self.point1.focus_set()
# Second point
self.point2 = ttk.Entry(master)
self.point2.grid(row=1, column=1)
self.point2.focus_set()
# labels
ttk.Label(text='First Point').grid(row=0, column=0)
ttk.Label(text='Second Point').grid(row=1, column=0)
ttk.Button(master, text="Done", width=10,command=self.callback).grid(row=5, column=2)
def callback(self):
""" get the contents of the Entries and exit the prompt"""
self.entry_contents=[self.point1.get(),self.point2.get()]
self.master.destroy()
master = tk.Tk()
GetPoints=GetEntry(master)
master.mainloop()
Points=GetPoints.entry_contents
return list(Points)
In python, functions are objects, as in get_values is an object.
Objects can have attributes.
Using these two, and the knowledge that we can't really return from a button command, we can instead attach an attribute to an already global object and simply use that as the return value.
Example with button
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_button_press(entry):
on_button_press.value = entry.get()
entry.quit()
def main():
root = tk.Tk()
entry = tk.Entry(root)
tk.Button(root, text="Get Value!", command=lambda e = entry : on_button_press(e)).pack()
entry.pack()
tk.mainloop()
return on_button_press.value
if __name__ == '__main__':
val = main()
print(val)
Minimalistic example
Similarly modules are also objects, if you want to avoid occupying global namespace extremely, you can attach a new attribute to the module you're using
See:
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
if __name__ == '__main__':
tk.my_value = lambda: [setattr(tk, 'my_value', entry.get()), root.destroy()]
root = tk.Tk()
entry = tk.Entry(root)
root.protocol('WM_DELETE_WINDOW', tk.my_value)
entry.pack()
tk.mainloop()
print(tk.my_value)

Tkinter: all radio buttons are selected

Why in this code when clicking a button when a new window opens, all the radio buttons are selected?
class CodeButton:
def __init__(self, root):
self.btn = Button(root, text="Code",width=20, height=1,bg="white", fg="black")
self.btn.bind("<Button-1>", make_code_window)
self.btn.pack()
def make_code_window(event):
new_root = Toplevel()
new_root.minsize(width=300, height=300)
var = IntVar()
var.set(0)
for i in range(8):
Radiobutton(new_root, text=str(i), variable=var, value=i).pack()
def main():
root = Tk()
root.minsize(width=400, height=250)
CodeButton(root)
root.mainloop()
It's got something to do with storing the IntVar in a local variable in the function that will be discarded as soon as the make_code_window() function returns. You can fix the problem by making the IntVar an attribute of the new_root window widget, so it will exist at least as long as the widget using it does.
The code in your example isn't very realistic in the sense that typically one would want to use the current value of the IntVar for something somewhere else in the Python code, but that wouldn't be possible since it's only stored temporarily in local variable which exists only during the execution of the function that created it.
try:
from tkinter import *
except ImportError: # Python 2
from Tkinter import *
class CodeButton:
def __init__(self, root):
self.btn = Button(root, text="Code",width=20, height=1,bg="white", fg="black")
self.btn.bind("<Button-1>", make_code_window)
self.btn.pack()
def make_code_window(event):
new_root = Toplevel()
new_root.minsize(width=300, height=300)
var = new_root.var = IntVar() # changed
var.set(0)
for i in range(8):
Radiobutton(new_root, text=str(i), variable=var, value=i).pack()
def main():
root = Tk()
root.minsize(width=400, height=250)
CodeButton(root)
root.mainloop()
main()
(Following-up on the discussion we were having in the comments section of my other answer.)
Yes, passing the IntVar as an argument to the event handler function is a little tricky—in fact it's sometimes called The extra arguments trick. ;-)
Here's an example of applying it to your code:
try:
from tkinter import *
except ImportError: # Python 2
from Tkinter import *
class CodeButton:
def __init__(self, root):
self.btn = Button(root, text="Code",width=20, height=1,bg="white", fg="black")
self.btn.bind("<Button-1>",
# Extra Arguments Trick
lambda event, var=root.var: make_code_window(event, var))
self.btn.pack()
def make_code_window(event, var): # note added "var" argument
new_root = Toplevel()
new_root.minsize(width=300, height=300)
var.set(-99) # deselect by using value not associated with any RadioButtons
for i in range(8):
Radiobutton(new_root, text=str(i), variable=var, value=i).pack()
def main():
root = Tk()
root.minsize(width=400, height=250)
root.var = IntVar() # create it here to give access to it in the rest of your code
CodeButton(root)
root.mainloop()
main()

Tkinter Python Window Crashing When Slider Updated [duplicate]

My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move every moment.
Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing root.mainloop() runs, runs, and keeps running, and the only thing it runs is the event handlers.
Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?
Right now, he came up with an ugly hack, tying his move() function to <b1-motion>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.
Use the after method on the Tk object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.
The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).
Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.
The revised code is as follows:
# Run tkinter code in another thread
import tkinter as tk
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
label = tk.Label(self.root, text="Hello World")
label.pack()
self.root.mainloop()
app = App()
print('Now we can continue running code while mainloop runs!')
for i in range(100000):
print(i)
When writing your own loop, as in the simulation (I assume), you need to call the update function which does what the mainloop does: updates the window with your changes, but you do it in your loop.
def task():
# do something
root.update()
while 1:
task()
Another option is to let tkinter execute on a separate thread. One way of doing it is like this:
import Tkinter
import threading
class MyTkApp(threading.Thread):
def __init__(self):
self.root=Tkinter.Tk()
self.s = Tkinter.StringVar()
self.s.set('Foo')
l = Tkinter.Label(self.root,textvariable=self.s)
l.pack()
threading.Thread.__init__(self)
def run(self):
self.root.mainloop()
app = MyTkApp()
app.start()
# Now the app should be running and the value shown on the label
# can be changed by changing the member variable s.
# Like this:
# app.s.set('Bar')
Be careful though, multithreaded programming is hard and it is really easy to shoot your self in the foot. For example you have to be careful when you change member variables of the sample class above so you don't interrupt with the event loop of Tkinter.
This is the first working version of what will be a GPS reader and data presenter. tkinter is a very fragile thing with way too few error messages. It does not put stuff up and does not tell why much of the time. Very difficult coming from a good WYSIWYG form developer. Anyway, this runs a small routine 10 times a second and presents the information on a form. Took a while to make it happen. When I tried a timer value of 0, the form never came up. My head now hurts! 10 or more times per second is good enough for me. I hope it helps someone else. Mike Morrow
import tkinter as tk
import time
def GetDateTime():
# Get current date and time in ISO8601
# https://en.wikipedia.org/wiki/ISO_8601
# https://xkcd.com/1179/
return (time.strftime("%Y%m%d", time.gmtime()),
time.strftime("%H%M%S", time.gmtime()),
time.strftime("%Y%m%d", time.localtime()),
time.strftime("%H%M%S", time.localtime()))
class Application(tk.Frame):
def __init__(self, master):
fontsize = 12
textwidth = 9
tk.Frame.__init__(self, master)
self.pack()
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Time').grid(row=0, column=0)
self.LocalDate = tk.StringVar()
self.LocalDate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalDate).grid(row=0, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
text='Local Date').grid(row=1, column=0)
self.LocalTime = tk.StringVar()
self.LocalTime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#be004e', fg = 'white', width = textwidth,
textvariable=self.LocalTime).grid(row=1, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Time').grid(row=2, column=0)
self.nowGdate = tk.StringVar()
self.nowGdate.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGdate).grid(row=2, column=1)
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
text='GMT Date').grid(row=3, column=0)
self.nowGtime = tk.StringVar()
self.nowGtime.set('waiting...')
tk.Label(self, font=('Helvetica', fontsize), bg = '#40CCC0', fg = 'white', width = textwidth,
textvariable=self.nowGtime).grid(row=3, column=1)
tk.Button(self, text='Exit', width = 10, bg = '#FF8080', command=root.destroy).grid(row=4, columnspan=2)
self.gettime()
pass
def gettime(self):
gdt, gtm, ldt, ltm = GetDateTime()
gdt = gdt[0:4] + '/' + gdt[4:6] + '/' + gdt[6:8]
gtm = gtm[0:2] + ':' + gtm[2:4] + ':' + gtm[4:6] + ' Z'
ldt = ldt[0:4] + '/' + ldt[4:6] + '/' + ldt[6:8]
ltm = ltm[0:2] + ':' + ltm[2:4] + ':' + ltm[4:6]
self.nowGtime.set(gdt)
self.nowGdate.set(gtm)
self.LocalTime.set(ldt)
self.LocalDate.set(ltm)
self.after(100, self.gettime)
#print (ltm) # Prove it is running this and the external code, too.
pass
root = tk.Tk()
root.wm_title('Temp Converter')
app = Application(master=root)
w = 200 # width for the Tk root
h = 125 # height for the Tk root
# get display screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
# calculate x and y coordinates for positioning the Tk root window
#centered
#x = (ws/2) - (w/2)
#y = (hs/2) - (h/2)
#right bottom corner (misfires in Win10 putting it too low. OK in Ubuntu)
x = ws - w
y = hs - h - 35 # -35 fixes it, more or less, for Win10
#set the dimensions of the screen and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.mainloop()

Categories