I am trying to create a harmless prank joke on my friends, and I want the background of a python tkinter window(not canvas) to change to a random colour every second, then, after ten rounds, it will destroy itself. The problem is that when root.config(background=random_colour)is called, it will not change it's background colour. The entire code is below:
from tkinter import *
import pyglet
import time
import random
root = Tk()
text = Label( padx = 1000, pady = 999, text = 'VIRUS!' )
text.pack()
text.config(font=('Courier', 44))
root.attributes("-fullscreen", True)
root.update()
I'm cutting this bit out because it's just a list of all the named colours in python(It's called COLOURS).
for x in range(0, 9):
colours_length = len(COLOURS)
number = random.randint(0, colours_length)
random_colour = COLOURS[number]
root.config(background=random_colour)
time.sleep(1)
root.update()
root.destroy()
I've took acw1668's advice from the comments section, and it works now. Turns out that the label was covering the entire root window, and that was why it wasn't working.
Related
when I click the button it call's cpuTemp function and it has a after loop init which causes my not responding window and it is show values of cpu percent in my python console so the question is why it is not working
'''
from tkinter import *
import psutil
import statistics
window = Tk()
# window size
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# window
window.attributes('-transparentcolor', 'blue')
window.resizable(True, True)
window.attributes('-alpha', 0.96)
window.config(cursor='crosshair')
window.attributes('-topmost', 0)
window.geometry(f"{screen_width}x{screen_height}+20+20")
window.state('zoomed')
window.title('Hello Python')
# windTemp
def cpuTemp(event):
#gettin temps
cpuTemps = [psutil.cpu_percent(0.5), psutil.cpu_percent(0.5), psutil.cpu_percent(0.5),
psutil.cpu_percent(0.5), psutil.cpu_percent(0.5)]
meanVal = statistics.mean(cpuTemps)
print(meanVal)
lbl.configure(text=f'{meanVal}%')
window.after(1000 , cpuTemp(event))
#button
btn = Button(window, text="This is Button widget", fg='blue')
btn.place(x=80, y=100)
btn.bind('<Button-1>', cpuTemp)
#label
lbl = Label(window , text='hi' , fg = "#0009ff0fc")
lblPlace = [ screen_width/2 , screen_height/2]
lbl.place(x=f'{lblPlace[0]}', y=f'{lblPlace[1]}')
window.mainloop()
# temp
this is not working can anyone fix this for me I would appreciate that.
it stills print in my pycharm consloe so why is my window not responding.
i am using pycharm as you might know now.
and I want to make this code working .
i am a python newbie so pls help it would mean a lot to me...
window.after(1000 , cpuTemp(event)) immediately runs cpuTemp(event) and passes the result to window.after. This creates an infinite loop since each call results in another call to the function.
The code needs to look something like this:
window.after(1000, cpuTemp, None)
The reason for None is that the function doesn't use the event, and the current event is relatively useless except for when the original event is being processed.
I have made most of this window already, and would prefer to not have to restart because of a hitch with a scrollbar not resizing properly. Problem being that the scrollbars appear way too small for the listboxes and I want them to span the whole height of each box respecitvely, but as of now they can only function if you spam the arrows as the actual scrolling bit can't move for lack of space. Any help would be appreciated, stuck on this for a while now. (Using python 3.8).
import tkinter as tk
from tkinter import *
setup = tk.Tk()
setup.title("Set Up Game")
setup.geometry("450x650")
setup.resizable(width=False, height=False)
select_Box = tk.Canvas(setup, width=450, height=496, bg="#cd3636")
select_Box.pack(padx=10)
listbox1 = Listbox(setup, width=33, height=30)
listbox1_win = select_Box.create_window(110,250, window=listbox1)
listbox2 = Listbox(setup, width=33, height=30)
listbox2_win = select_Box.create_window(320,250, window=listbox2)
scroll1 = Scrollbar(setup)
scroll1_win = select_Box.create_window(200,250, window=scroll1)
scroll2 = Scrollbar(setup)
scroll2_win = select_Box.create_window(410,250, window=scroll2)
listbox1.config(yscrollcommand = scroll1.set, selectmode=SINGLE)
scroll1.config(command = listbox1.yview)
listbox2.config(yscrollcommand = scroll2.set, selectmode=SINGLE)
scroll2.config(command = listbox2.yview)
nameArray = ["Bulbasaur", "Ivysaur", "Venasaur", "Charmander", "Charmelion", "Charazard", "Squirtle", "Wartortle", "Blastoise", "Lucario", "Garchomp", "Gengar", "Snorlax", "Reuniclus", "Joel","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder"]
for item in nameArray:
listbox1.insert(END, item)
setup.mainloop()
If you want to use Canvas.create_window to place all of your widgets, all you have to do is define the height of your scrollbar (you may need to play around with the numbers a little to get it to the right size).
So the edited snippet from your code will be:
scroll1 = Scrollbar(setup)
scroll1_win = select_Box.create_window(200,
250,
height=480, # this is all you're missing!
window=scroll1)
I am looking for an efficient way to rapidly display images with tkinter, and I mean like really fast. Currently I have this code:
from tkinter import*
import threading
import time
root = Tk()
root.geometry("200x200")
root.title("testing")
def img1():
threading.Timer(0.2, img1).start()
whitei = PhotoImage(file="white.gif")
white = Label(root, image=whitei)
white.image = whitei
white.place(x=0, y=0)
def img2():
threading.Timer(0.2, img2).start()
blacki = PhotoImage(file="black.gif")
black = Label(root, image=blacki)
black.image = blacki
black.place(x=0, y=0)
img1()
time.sleep(0.1)
img2()
root.mainloop()
Essentially the code just displays a black and white image but it puts my CPU at 100% usage and is pretty slow no matter how small I make the amount of time each picture is displayed for. Is there a faster, more efficient way to do this?
As mentioned, I would suggest using after. You aren't really supposed to alter any tkinter objects outside your main thread. Also, creating a new object each time isn't the most efficient. Here's something I would try:
import tkinter as tk
root = tk.Tk()
root.geometry("200x200")
root.title("testing")
whitei = tk.PhotoImage(file="white_.gif")
blacki = tk.PhotoImage(file="black_.gif")
label = tk.Label(root, image=whitei)
label.image1 = whitei
label.image2 = blacki
label.place(x=0, y=0)
time_interval = 50
def img1():
root.after(time_interval, img2)
label.configure(image=whitei)
def img2():
root.after(time_interval, img1)
label.configure(image=blacki)
root.after(time_interval, img1)
root.mainloop()
You do not need to use threading. 2nd unless you are using sleep() inside of a separate thread you should never use sleep in a tkinter application. sleep() interrupts the mainloop and will cause tkinter to freeze up until sleep is finished. This is 99.9% of the time not what you want to do so here you should use after() for any timed events.
You can simple create each label for each image and then with a tracking variable raise the correct label to the top.
Here is a simple example.
from tkinter import *
root = Tk()
root.geometry("200x200")
root.title("testing")
current_image = ""
black_image = PhotoImage(file="black.gif")
white_image = PhotoImage(file="white.gif")
black_label = Label(root, image=black_image)
white_label = Label(root, image=white_image)
black_label.image = black_image
white_label.image = white_image
black_label.grid(row=0, column=0)
white_label.grid(row=0, column=0)
def loop_images():
global current_image, black_image, white_image
if current_image == "white":
black_label.tkraise(white_label)
current_image = "black"
else:
white_label.tkraise(black_label)
current_image = "white"
root.after(100, loop_images)
loop_images()
root.mainloop()
I´m trying to use tkinter in order to show a popup window in front of all other windows that reminds me of something through a text displayed in the canvas. I want that the window pops up during some time, eg 5 seconds, and then dissapear for other time. I need this to repeat in a loop. When i tried to do it, a window appear but without the text and the specified dimensions. Here is the code:
from tkinter import *
from time import sleep as s
for i in range(5):
root = Tk()
root.lift()
root.attributes('-topmost',True)
canvas = Canvas(root,width=700,height=100)
canvas.pack()
canvas.create_text(350,50,text='Registrar rabia'+str(i),font=
('fixedsys','25'))
print('Hola')
s(1)
root.destroy()
s(1)
Also, is there a more pythonic way to do it?
EDIT:
from tkinter import *
root = Tk()
for _ in range(6):
#root.deiconify()
root.attributes('-topmost',True)
root.title("About this application...")
about_message = 'Este es el mensaje'
msg = Message(root, text=about_message)
msg.pack()
button = Button(root, text="Dismiss", command=root.withdraw)
button.pack()
root.after(1000)
It didn´t work. I need only one message and one button, and in the code above,
python shows 6 messages and 6 buttons... Also i need to put a delay between appearances but i can´t understand how to use the after method in this particular case.
Im trying to make a little program that endlessly prints out numbers inside GUI window, I can not find a way to print the out put of the function in a text box inside the GUI window instead of the python shell, please help, here is my code so far...
import sys
from tkinter import *
root = Tk()
def number(event):
x = 420
while True:
x +=420
print(x^70)
button_1 = Button(root, text="Start...")
button_1.bind("<Button-1>", number)
button_1.pack()
root.mainloop()
Thanks Harvey
You'll find it hard to constantly insert a value into a widget. The widget does not update with each insert. You can think of it has having a temporary variable for it. It can be accessed during the loop (as shown with print). However you'll notice that the widget itself doesn't update until the loop is over. So if you have while True then your widget will never update, and so you won't have the numbers streaming into the widget.
import sys
from tkinter import *
root = Tk()
def number():
x = 420
while x < 8400: # Limit for example
x +=420
textbox.insert(END, str(x^70)+'\n')
print(textbox.get(1.0, END)) # Print current contents
button_1 = Button(root, text="Start...", command=number) #Changed bind to command, bind is not really needed with a button
button_1.pack()
textbox = Text(root)
textbox.pack()
root.mainloop()