How to make arrow move randomly on a Canvas image? - python

I am making a random number generator and it's like this in the picture.
import random
import time
root = Tk()
root.title("Random Picker V.2")
root.iconbitmap(r'Icon.ico')
canvas = Canvas(root, width=1080, height=720)
canvas.pack()
good = PhotoImage(file='mrwallpapers.png')
goodha = PhotoImage(file='Very good.png')
canvas.create_image(50, 10, image=good)
canvas.create_text(530, 70, fill='white', text='Random Picker V.2', font=("Arial", 40, "underline"))
canvas.create_text(530, 130, fill='white', text='Random Arrow Moves', font=("Arial", 26))
canvas.create_text(530, 700, fill='yellow', text='This was made by Che 1/10 2019', font=("Arial", 15))
item = canvas.create_text(534, 280, fill='white', text='0', font=("Arial", 35))
item1 = canvas.create_text(263, 280, fill='white', text='0', font=("Arial", 35))
item2 = canvas.create_text(800, 280, fill='white', text='0', font=("Arial", 35))
arrow = canvas.create_image(540, 200, image=goodha)
def login():
random1 = random.randint(1, 36)
random2 = random.randint(1, 36)
random3 = random.randint(1, 36)
canvas.itemconfig(item, text=random1)
canvas.itemconfig(item1, text=random2)
canvas.itemconfig(item2, text=random3)
def login1():
random4 = random.randint(1, 45)
random5 = random.randint(1, 45)
random6 = random.randint(1, 45)
canvas.itemconfig(item, text=random4)
canvas.itemconfig(item1, text=random5)
canvas.itemconfig(item2, text=random6)
def login2():
choice = ['260', '-265']
random10 = random.choices(choice)
canvas.move(arrow, random10, 0)
def randomnumber():
canvas.itemconfig(item, fill='blue')
root.after(500, randomnumber)
canvas.itemconfig(item, fill='red')
root.after(500, randomnumber)
gifted = Button(root, font=("Arial", 25), text="Gifted Pick (36)", command=login)
gifted.place(rely=0.59, relx=0.37, relwidth=0.25, relheight=0.07)
normal = Button(root, font=("Arial", 22), text="Normal Pick (45)", command=login1)
normal.place(rely=0.69, relx=0.37, relwidth=0.25, relheight=0.07)
photo = PhotoImage(file='color.png')
spinm = Button(root, image=photo, fg='white', font=("Arial", 22), command=login2)
spinm.place(rely=0.59, relx=0.62, relwidth=0.05, relheight=0.17)
root.mainloop()
I want the canvas image (arrow) moves to left or right or middle randomly with slide animation. Is that possible for it and how do I do it? Because it doesn't work for the code I did (login2) it moves out of the frame and I also want an arrow to slide to left right or middle randomly because it's a random number generator.

Related

choose one color of two for object and when click on button, then starts drawing with turle in python

`I am creating a loging page where user needs to choose color(objekta krāsa) for car. User need to chose from
blue(Zilā krāsa) and black(melnā krāsa) colors in the drop down menu and when button "Ienākt" is clicked it starts shoud start drawing a car with selected,but now when i pres ienākt it shows blank page and also when both drop down menus are emty its still works and doesnt show error. I been trying to fix this for all evening, and i still learning.How to get that when users choses color and clicks ienākt buttom drawing starts at he chosen color?and when all the menus are emty it should not work.
i would appreciate your help!
from tkinter import *
from tkinter import messagebox
import tkinter as tk
from tkinter import ttk
import turtle
root = Tk()
root .title('Ienākt')
root .geometry('925x500+300+200')
root. configure(bg="#fff")
root .resizable(False, False)
img = PhotoImage(file=r'C:\Users\Inga\Downloads\ienakt.png')
Label(root, image=img, bg='white').place(x=5, y=50)
frame = Frame(root, width=350, height=400, bg="white")
frame. place(x=480, y=70)
heading = Label(frame, text='Ienākt', fg='#57a1f8', bg='white',
font=('Microsoft YaHei UI Light', 23, 'bold'))
heading.place(x=100, y=5)
# -----
def on_enter(e):
user.delete(0, 'end')
def on_leave(e):
name = user.get()
if name == '':
user.insert(0, 'E-pasts')
user = Entry(frame, width=25, fg='#000000', border=0,
bg="white", font=('Microsoft YaHei UI Light', 11))
user.place(x=30, y=80)
user.insert(0, 'E-pasts')
user.bind('<FocusIn>', on_enter)
user.bind('<FocusOut>', on_leave)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=107)
# -----
def on_enter(e):
password.delete(0, 'end')
def on_leave(e):
name = password.get()
if name == '':
password.insert(0, 'Parole')
password = Entry(frame, width=25, fg='#000000', border=0,
bg="white", font=('Microsoft YaHei UI Light', 11))
password.place(x=30, y=150)
password.insert(0, 'Parole')
password.bind('<FocusIn>', on_enter)
password.bind('<FocusOut>', on_leave)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=177)
# ----tekts krasa
label = Label(root, text="Objekta krāsa", width=41,
font=("Microsoft YaHei UI Light", 11), bg='white')
label.place(x=467, y=291)
# ---IZVĒLE-krāsa
col = tk.StringVar()
col_chs = ttk.Combobox(frame, width=45, textvariable=col, state='readonly')
col_chs['values'] = ('Melnā krāsa', 'Zilā krāsa')
col_chs.place(x=25, y=249)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=247)
# ----objekts
label = Label(root, text="Objekts", width=41,
font=("Microsoft YaHei UI Light", 11), bg='white')
label.place(x=467, y=361)
# ----Izvēle-- objekts
col = tk.StringVar()
col_chs = ttk.Combobox(frame, width=45, textvariable=col, state='readonly')
col_chs['values'] = ('Mašīna',)
col_chs.place(x=25, y=318)
Frame(frame, width=295, height=2, bg='#000000').place(x=25, y=317)
# ----
def draw_object():
screen = turtle.Screen()
color = col_chs.get()
car = turtle.Turtle()
if color == 'Melnā krāsa':
car.color("black")
car.fillcolor("black")
car.begin_fill()
car.forward(370)
car.left(90)
car.forward(50)
car.left(90)
car.forward(370)
car.left(90)
car.forward(50)
car.end_fill()
# Below code for drawing window and roof
car.penup()
car.goto(100, 50)
car.pendown()
car.setheading(45)
car.forward(70)
car.setheading(0)
car.forward(100)
car.setheading(-45)
car.forward(70)
car.setheading(90)
car.penup()
car.goto(200, 50)
car.pendown()
car.forward(49.50)
car.penup()
car.goto(100, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
car.penup()
car.goto(300, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
turtle.exitonclick()
elif color == 'Zilā krāsa':
car.color("blue")
car.fillcolor("blue")
car.penup()
car.goto(0, 0)
car.pendown()
car.begin_fill()
car.forward(370)
car.left(90)
car.forward(50)
car.left(90)
car.forward(370)
car.left(90)
car.forward(50)
car.end_fill()
# Below code for drawing window and roof
car.penup()
car.goto(100, 50)
car.pendown()
car.setheading(45)
car.forward(70)
car.setheading(0)
car.forward(100)
car.setheading(-45)
car.forward(70)
car.setheading(90)
car.penup()
car.goto(200, 50)
car.pendown()
car.forward(49.50)
car.penup()
car.goto(100, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
car.penup()
car.goto(300, -10)
car.pendown()
car.begin_fill()
car.circle(20)
car.end_fill()
turtle.exitonclick()
# ---
def login():
user_name = user.get()
user_password = password.get()
if user_name == "E-pasts" or user_password == "Parole":
messagebox.showerror("Kļūda", "Aizpildiet visus laukus")
else:
if user_name == "admin" and user_password == "admin":
messagebox.showinfo("Paziņojums", "Ienācāt")
draw_object()
turtle.mainloop()
else:
messagebox.showerror("Kļūda", "Nepareizs e-pasts vai parole")
# ---- ieiešanas poga
login_button = Button(frame, width=41, pady=7,
text='Ienākt', bg='#57a1f8', fg='white', command=draw_object)
login_button["command"] = draw_object
login_button.place(x=23, y=360)
def open_login_page():
exec(open("path/to/login_page_code.py").read())
root.mainloop()
`
At first i tried to make when button is clicked it call the draw function and then draw and then i added if and elif in the draw_object and try to change some little things but that didnt help.
i would appreciate your help!

Problem when export csv using Pandas (file cannot read chinese char)

I am trying to create flashcard game, but I have problem when trying to export dict to csv using pandas.
My dictionary has contained some Chinese letters and pinyin.
When I have played with multiple encodings, seem sometime Chinese letter can be read but pinyin is unreadable, sometimes its vice versa.
I'm not sure what is the issue about my code. please help me.
Thank you very much
Remark
for pinyin Im using slash or back-slash or dash to indicate tone
Ex. bàn tiān,
when import to csv, the program still can read those tone symbol, but not when export.
Example
export csv is on line 109-110
import random
import pandas as pd
from tkinter import *
from PIL import Image, ImageTk
windows = Tk()
windows.geometry(r"300x360")
windows.config(bg='#f7f5dd')
my_pic = Image.open(r"C:\\Users\\xx\\PycharmProjects\\flashcard\\Picture1.png")
scale_factor = 0.3
resized = my_pic.resize((int(712 * scale_factor), int(667 * scale_factor)))
img = ImageTk.PhotoImage(resized)
canvas = Canvas(width=235, height=235, bg="#f7f5dd", highlightthickness=0)
canvas.create_image(120, 120, image=img)
canvas.grid(column=1, row=1, pady=20, padx=30, columnspan=3)
know_button = Button()
dont_know_button = Button()
already_know_list = []
pix1 = Image.open(r"C:\Users\xx\PycharmProjects\flashcard\correct.png")
pix2 = Image.open(r"C:\Users\xx\PycharmProjects\flashcard\wrong.png")
scale_factor2 = 0.15
resized1 = pix1.resize((int(274 * scale_factor2), int(275 * scale_factor2)))
resized2 = pix2.resize((int(274 * scale_factor2), int(275 * scale_factor2)))
img1 = ImageTk.PhotoImage(resized1)
img2 = ImageTk.PhotoImage(resized2)
know_button.config(image=img1, bg="#f7f5dd", highlightthickness=0)
dont_know_button.config(image=img2, bg="#f7f5dd", highlightthickness=0)
know_button.grid(column=0, row=2, columnspan=2)
dont_know_button.grid(column=3, row=2, columnspan=2)
data = pd.read_csv(r"C:\\Users\\xx\\PycharmProjects\\flashcard\\hsk_vocabs_1_5.csv")
custom_data = data
number = random.randint(0, len(data))
chn_obj = canvas.create_text(120, 140, text=f"{data['Chinese'][number]}\n{data['Pinyin'][number]}", fill="white",
font=('Dosis SemiBold', 20, 'bold'), anchor='center')
five_sec_label = Label()
five_sec_label.config(text="3", font=('Dosis SemiBold', 20, 'bold'), bg="#f7f5dd")
five_sec_label.grid(column=1, row=2, columnspan=3)
init_sec = 3
timer = None
def clock(total_second):
global chn_obj, timer, init_sec
if total_second >= 0:
timer = windows.after(1000, clock, total_second - 1)
five_sec_label.config(text=f"{total_second}", font=('Corrier', 20, 'bold'))
else:
canvas.itemconfig(chn_obj, text="")
chn_obj = canvas.create_text(120, 140, text=f"{data['English'][number]}", fill="black",
font=('Dosis SemiBold', 15, 'bold'), anchor='center')
init_sec = 0
def next_word():
global number, chn_obj, timer, init_sec
init_sec = 3
canvas.itemconfig(chn_obj, text="")
chn_obj = canvas.create_text(120, 140, text=f"{data['Chinese'][number]}\n{data['Pinyin'][number]}", fill="white",
font=('Dosis SemiBold', 20, 'bold'), anchor='center')
windows.after_cancel(timer)
five_sec_label.config(text="")
clock(init_sec)
unknown_word = []
def already_know():
global already_know_list, number
already_know_list.append(number)
while number in already_know_list:
number = random.randint(0, len(data))
next_word()
def append_unknown_words():
global number, init_sec
if init_sec != 0:
return
else:
unknown_word.append(data['Chinese'][number])
number = random.randint(0, len(data))
next_word()
chinese_list = []
pinyin_list = []
english_list = []
def export_when_finished():
global unknown_word, chinese_list, pinyin_list, english_list
unknown_file = {
"Chinese": chinese_list,
"Pinyin": pinyin_list,
"English": english_list
}
for item in unknown_word:
chinese_list.append(data[data["Chinese"] == item]["Chinese"].values[0])
pinyin_list.append(data[data["Chinese"] == item]["Pinyin"].values[0])
english_list.append(data[data["Chinese"] == item]["English"].values[0])
df = pd.DataFrame(unknown_file)
df.to_csv('Unknown_Words.csv', encoding="utf-8")
exit()
know_button.config(command=already_know)
dont_know_button.config(command=append_unknown_words)
stop_game_n_export = Button()
stop_game_n_export.config(text="Stop and Export Unknown Words", font=('Dosis SemiBold', 10, 'bold'),
command=export_when_finished)
stop_game_n_export.grid(column=0, row=0, columnspan=3, rowspan=1)
clock(init_sec)
windows.mainloop()

How Can I integrate Python Turtle into Tkinter

from tkinter import *
import turtle
def RunTurtle():
import turtle
window = turtle.Screen()
window.bgcolor("light green")
window.title("Turtle")
t = turtle.Turtle()
t.speed(20)
def MyTurtleFunc(Fl, Sl, f, rin, ro, c, w):
t.color(c)
t.width(w)
for _ in range(Fl):
for _ in range(Sl):
t.forward(f)
t.right(rin)
t.right(ro)
MyTurtleFunc(36, 4, 100, 90, 10, "blue", 4)
def RunGUI():
master = Tk()
master.title("Project")
canvas = Canvas(master, height=1080, width=1920)
canvas.pack()
def RUN():
RunTurle()
TopFrame = Frame(master, bg='light green')
TopFrame.place(relx=0.04, rely=0.04, relwidth=0.91, relheight=0.6)
MiddleFrame = Frame(master, bg='light blue')
MiddleFrame.place(relx=0.04, rely=0.66, relwidth=0.91, relheight=0.06)
BottomFrame = Frame(master, bg='orange')
BottomFrame.place(relx=0.04, rely=0.74, relwidth=0.91, relheight=0.25)
TopLabel = Label(TopFrame, bg='light green', text="Drawing Robot", font="calibri 15 bold", foreground="black")
TopLabel.pack(padx=5, pady=5)
LabelBottom = Label(BottomFrame, bg='orange', text="Debug Area ", font="vendara 15 bold ", foreground="black")
LabelBottom.pack(padx=0.1, pady=0.1)
LabelBottomText = Text(BottomFrame, height=10.5, width=180)
LabelBottomText.tag_configure('style', foreground='grey', font=('calibri', 10, 'bold'))
LabelBottomText.pack()
fronttext = "..."
LabelBottomText.insert(END, fronttext, 'style')
RunProgram = Button(MiddleFrame, text="RUN PROGRAM", foreground="black", command=RUN)
RunProgram.pack(padx=0.2, pady=0.2, side=LEFT)
master.mainloop()
I designed interface my entry level program.I divide this three part.TopFrame must show turtle.Middle Frame has button which help us to start the program .Bottom Frame has debug area. I want to integrate "RunTurtle()" function into TopFrame.When the user click "RUN PROGRAM" button ,interface will open and turtle will draw pattern into TopFrame.How can I do this ? thank you...
def RUN():
RunTurle()
should be
def RUN():
RunTurtle()
and run the function RunGUI() its works

How to clear a Label Text of tkinter

I want to clear the output result of the equation. But when I press the clear button it gives an error
"NameError: name 'CalculationOutput' is not defined"
How do I solve this problem.
import tkinter as tk
compression = ""
GuiRoot = tk.Tk()
MainCanvas = tk.Canvas(GuiRoot, width=500, height=400, relief="raised")
MainCanvas.pack()
DesignText1 = tk.Label(GuiRoot, text="Calculate the Square Root")
DesignText1.config(font=("halvetica", 14))
MainCanvas.create_window(250, 25, window=DesignText1)
DesignText2 = tk.Label(GuiRoot, text="Type your number")
DesignText2.config(font=("halvetica", 10))
MainCanvas.create_window(250, 100, window=DesignText2)
UserEntryBox = tk.Entry(GuiRoot)
MainCanvas.create_window(250, 200, window=UserEntryBox)
def GetSquareRoot():
x = UserEntryBox.get()
DesignText3 = tk.Label(GuiRoot, text="The Square Root of " + x + ' is:', font=("halvetica", 10))
MainCanvas.create_window(250, 260, window=DesignText3)
CalculationOutput = tk.Label(GuiRoot, text=float(x)**0.5, font=("halvetica", 10, "bold"))
MainCanvas.create_window(250, 280, window=CalculationOutput)
CalculationButton = tk.Button(text="Get the Square Root", command=GetSquareRoot, bg="brown", fg='white', font=('halvetica', 9, 'bold'))
MainCanvas.create_window(250, 230, window=CalculationButton)
def ClearButtonFunc():
global compression
compression = ""
CalculationOutput.set("")
ClearButton = tk.Button(GuiRoot, text="Clear Text", command=ClearButtonFunc)
MainCanvas.create_window(250, 320, window=ClearButton)
GuiRoot.mainloop()

Changing the colour of tkinter rectangles using Entry and button

Super new to coding, I have a tkinter GUI with 5 rectangles, an entry box, and a button labelled go. I want to be able to change the color of the rectangles based on the number I enter into the entry box after I hit go. I don't think i'm close? but i have no idea how to proceed. Help would be appreciated. Thanks
from tkinter import *
the_window = Tk()
the_window.title('Show Text Count')
def changelbl():
number=(numberx.get())
if (numberx == 1):
label1.config(fill='green')
numberx=StringVar()
canvas = Canvas(the_window, width=270, height=20)
canvas.pack()
label1 = canvas.create_rectangle(0, 0, 50, 20, fill='grey')
label2 = canvas.create_rectangle(55, 0, 105, 20, fill='grey')
label3 = canvas.create_rectangle(110, 0, 160, 20, fill='grey')
label4 = canvas.create_rectangle(165, 0, 215, 20, fill='grey')
label5 = canvas.create_rectangle(220, 0, 270, 20, fill='grey')
Entrybox = Entry(the_window, bg='grey', width=15, textvariable=numberx)
Entrybox.pack(padx=(60,0), side=LEFT)
Gobutton = Button(the_window, text='Go',command=changelbl)
Gobutton.config(height=1, width=5)
Gobutton.pack(padx=(15,0), side=LEFT)
Here is a corrected version that changes the rectangle colors upon entry of a number in the entrybox, and pressing the Go button:
from tkinter import *
the_window = Tk()
the_window.title('Show Text Count')
def on_Go_button():
try:
num = int(entrybox.get())
except:
num = 3
num = num % 5
canvas.itemconfig(num, fill='green')
numberx=StringVar()
canvas = Canvas(the_window, width=270, height=20)
canvas.pack()
pos = [(0, 0, 50, 20), (55, 0, 105, 20), (110, 0, 160, 20), (165, 0, 215, 20), (220, 0, 270, 20)]
rectangles = [None for _ in range(5)]
for idx in range(5):
rectangles[idx] = canvas.create_rectangle(*pos[idx], fill='grey')
entrybox = Entry(the_window, bg='grey', width=15, textvariable=numberx)
entrybox.pack(padx=(60,0), side=LEFT)
gobutton = Button(the_window, text='Go',command=on_Go_button)
gobutton.config(height=1, width=5)
gobutton.pack(padx=(15,0), side=LEFT)
the_window.mainloop()
This may not be as simple of an answer as you were looking for, but hopefully it will be of some help.
I thought that creating a class would be a better approach for getting your desired result. I also changed changelbl to allow for multiple color options to be retrieved from a dictionary.
In your code, you were missing the line, the_window.mainloop() which will start start running your tkinter window.
from tkinter import *
class ColorBoxes:
def __init__(self, the_window):
self.root = the_window
self.root.title('Show Text Count')
self.canvas = Canvas(self.root, width=270, height=20)
self.canvas.pack()
self.label1 = self.canvas.create_rectangle(0, 0, 50, 20, fill='grey')
self.label2 = self.canvas.create_rectangle(55, 0, 105, 20, fill='grey')
self.label3 = self.canvas.create_rectangle(110, 0, 160, 20, fill='grey')
self.label4 = self.canvas.create_rectangle(165, 0, 215, 20, fill='grey')
self.label5 = self.canvas.create_rectangle(220, 0, 270, 20, fill='grey')
self.entry_box = Entry(self.root, bg='grey', width=15,)
self.entry_box.pack(padx=60, side=LEFT)
self.go_button = Button(self.root, text='Go', command=self.changelbl)
self.go_button.config(height=1, width=5)
self.go_button.pack(padx=15, side=LEFT)
def changelbl(self):
number = self.entry_box.get()
fill_colors = {
'1': 'green',
'2': 'yellow',
'3': 'red'
# can add more colors to this dictionary if needed
}
self.canvas.itemconfig(self.label1, fill=fill_colors.get(number))
self.canvas.itemconfig(self.label2, fill=fill_colors.get(number))
self.canvas.itemconfig(self.label3, fill=fill_colors.get(number))
self.canvas.itemconfig(self.label4, fill=fill_colors.get(number))
self.canvas.itemconfig(self.label5, fill=fill_colors.get(number))
the_window = Tk()
ColorBoxes(the_window)
the_window.mainloop()
Again, this may be more than you were looking for, but hopefully you can pick up on what is going on and learn a bit! Good luck!

Categories