Run Label with tkinter. Please refer to [tkinter] Try using Label etc. for the basic part such as how to arrange Frame and Label.
A program that starts moving in the opposite direction when both ends of label
are about to come out from both ends of Frame.
from tkinter import ttk
import tkinter
def move(flag,i):
if(flag==True):
i-=1
else:
i+=1
if(i==0):
flag=False
elif(i+label.winfo_reqwidth()==400):
flag=True
label.place(x=i,y=150)
label.after(4,lambda: move(flag,i))
w,h="400","300"
root=tkinter.Tk()
ttk.Style().configure("TP.TFrame", background="snow")
f=ttk.Frame(master=root,style="TP.TFrame",width=w,height=h)
f.pack()
fontsize=20
label=ttk.Label(master=root,text="Labeltext",font=("Meiryo",fontsize),foreground="red",background="green")
i=400
flag=True
move(flag,i)
root.mainloop()
To reproduce how the Label "moves", recursively execute the function that moves __1pixel to the left (right) __. That is, the move function is called within the move function that moves 1 pixel label
.
label.after (n, f)
executes the function f after n milliseconds, so label.after (4, lambda: move (flag, i))
sets the x coordinate of label
to 1. Execute the move function again after 4 milliseconds on the line (line 14) just before the end of the move function to be changed. Doing so creates an infinite loop of the move function and makes the Label appear to work.
A bind method that can execute the function f when an object is clicked (left-click because it is <1>, right-click if <3>), such as label.bind (<1>, f)
. In the after method that can execute the function g after n milliseconds for a certain object like label.after (n, g)
introduced earlier, the function name is put in the second argument, but if it is as it is Cannot pass arguments. If you write label.after (n, move (flag, i))
, an error will occur. This is because move (flag, i) ()
is actually called.
I would like to introduce two ways to solve this.
__ (1) Notation with lambda (anonymous function) __
That is, it should be label.after (n, lambda: move (flag, i))
.
For lambda, please refer to Python lambda is easy to understand.
__ (2) Nesting functions __
Nested = "nested". In Python you can define another function within a function. Here, as introduced earlier, label.after (n, move (flag, i))
actually says not move (flag, i)
but move (flag, i) ().
So, you can forcibly create that shape.
I don't want to recommend this because the code tends to be dirty (while saying that Twitter search results are sent like a certain video site [python] It's a secret that some spaghettis contain many nested functions).
The above sample code works correctly if you do the following.
from tkinter import ttk
import tkinter
def move(i):
def x():
global i
global flag
if(i==0):
flag=False
elif(i+label.winfo_reqwidth()==400):
flag=True
if(flag==True):
i-=1
else:
i+=1
label.place(x=i,y=150)
label.after(4,move(i))
return x
(Omission)
i=400
flag=True
label.after(1,move(i))
root.mainloop()
dirty.
Recommended Posts