Related
I ran into this problem and don't know how to solve it.
When I press the "generate" button(self.gen), my picture 11 changes to picture 22.
BUT I need the image 11 to NOT change when the button is clicked and an error occurs(messagebox.showerror pops up) OR so that after closing the messagebox.showerror, picture 22 changes to 11
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, width = 15, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=230, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, width = 15, text="Delete", command=lambda:[self.delete(),self.clicked2()])
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, width = 15, text="Exit", command=lambda: [self.clicked3(), quit()])
self.exit.grid(column=6, row=6)
self.i = Button(self.window, width = 8,text = "i", font = ("Eras Bold ITC", 10) , command = self.inf)
self.i.grid(row = 0,column = 6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
else:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
def delete(self):
self.txt4.delete(0, END)
self.txt3.delete(0, END)
self.txt2.delete(0, END)
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.config(state="disabled") # disable the text box
def clicked2(self):
print("clicked2")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def clicked3(self):
messagebox.showinfo("Це Звірополіс. Будь-хто може бути будь-ким.", "Хто сказав, що неможливе недосяжне?! Пошкодуйте цього дивака.")
def inf(self):
messagebox.showinfo("Info", "Лисичка замахалась")
app = App()
is it possible to implement this through tkinter?
Change the command argument of self.gen to:
self.gen = Button(self.window, width = 15, text="Generate", command=self.gen1)
And move the call to clicked1() into the if block of gen1() so it will only be called when conditions are accepted
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
self.clicked1() # call the 'clicked1' method
else:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
There are Three code files
Main.py :-
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from sqlite3 import *
from turtle import home
import home
class LoginWindow(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title("login")
self.geometry("400x300")
s = Style()
s.configure('Header.TFrame', background = 'blue')
header_frame = Frame(self, style= 'Header.TFrame')
header_frame.pack(fill = X)
s.configure('Header.TLabel', background = 'blue', foreground = 'white', font = ('Arial', 25))
header_label = Label(header_frame,text="Office contact book", style='Header.TLabel')
header_label.pack(pady=10)
s.configure('Content.TFrame', background = 'white')
content_frame = Frame(self, style= 'Content.TFrame')
content_frame.pack(fill= BOTH, expand= TRUE)
login_frame = Frame(content_frame, style= 'Content.TFrame')
login_frame.place(relx=.5, rely=.5, anchor=CENTER)
s.configure('Login.TLabel', background = 'white', font = ('Arial', 15))
username_label = Label(login_frame, text= 'Username:', style= 'Login.TLabel')
username_label.grid(row= 0, column= 0, pady= 5)
self.username_entry = Entry(login_frame,width= 15, font = ('Arial', 15))
self.username_entry.grid(row= 0, column= 1, pady= 5)
password_label = Label(login_frame, text= 'Password:', style= 'Login.TLabel')
password_label.grid(row= 1, column= 0, pady= 5)
self.password_entry = Entry(login_frame,width= 15, font = ('Arial', 15), show= '*')
self.password_entry.grid(row= 1, column= 1, pady= 5)
s.configure("Login.TButton", font = ('Arial', 15))
login_button = Button(login_frame, text ="Login",width= 15, style= 'Login.TButton', command= self.login_button_click)
login_button.grid(row=3, column= 1, pady= 5)
def login_button_click(self):
con = connect('contacts.db')
cur = con.cursor()
cur.execute("select * from Login where Username = ? and Password = ?", (self.username_entry.get(), self.password_entry.get()))
row = cur.fetchone()
if row is not None:
self.destroy()
home.HomeWindow()
else:
messagebox.showerror("Error message", "Incorrect username or password.")
if __name__ == '__main__':
lw = LoginWindow()
lw.mainloop()
Home.py :-
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from sqlite3 import *
from turtle import width
import main
import changepassword
class HomeWindow (Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title("Home")
self.state('zoomed')
s = Style()
s.configure('Header.TFrame', background = 'blue')
header_frame = Frame(self, style= 'Header.TFrame', height= 50)
header_frame.pack(fill = X)
s.configure('Header.TLabel', background = 'blue', foreground = 'white', font = ('Arial', 25))
header_label = Label(header_frame,text="Office contact book", style='Header.TLabel')
header_label.pack(pady=10)
navigation_frame = Frame(self, style= 'Header.TFrame', width= 50)
navigation_frame.pack(side= LEFT, fill= Y)
s.configure('Navigation.TButton', width= 30, font= ('Arial', 15))
manage_contacts_button = Button(navigation_frame, text= 'Manage contacts', style= 'Navigation.TButton')
manage_contacts_button.pack(ipady= 10, pady= 2)
def change_password_button_click (self):
changepassword.ChangePasswordFrame(content_frame)
change_password_button = Button(navigation_frame, text= 'Change password', style= 'Navigation.TButton', command= self.change_password_button_click(*args))
change_password_button.pack(ipady= 10, pady= 2)
def logout_button_click (self):
self.destroy()
main.LoginWindow()
# logout_button = Button(navigation_frame, text= 'Logout', style= 'Navigation.TButton', command= self.logout_button_click)
# logout_button.pack(ipady= 10, pady= 2)
s.configure('Navigation.TFrame', background = 'white')
content_frame = Frame(self, style= 'Navigation.TFrame')
content_frame.pack(fill= BOTH, expand= TRUE)
# lw = HomeWindow()
# lw.mainloop()
changepassword.py :-
from tkinter import *
from tkinter.ttk import *
class ChangePasswordFrame (Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
s = Style()
s.configure('TFrame', background = 'white')
s.configure('TLabel', background = 'white', font = ('Arial', 25))
self.place(relx = .5, rely = .5, anchor = CENTER)
old_password_label = Label(self, text= "Old Password:")
old_password_label.grid(row=0, column= 0)
old_password_entry = Entry(self)
old_password_entry.grid(row=0, column=1)
New_password_label = Label(self, text= "New Password:")
New_password_label.grid(row=1, column= 0)
New_password_entry = Entry(self)
New_password_entry.grid(row=1, column=1)
confrim_password_label = Label(self, text= "Confrim new Password:")
confrim_password_label.grid(row=2, column= 0)
confrim_password_entry = Entry(self)
confrim_password_entry.grid(row=2, column=1)
change_password_button = Button(self, text = "Change Password")
change_password_button.grid(row = 3, column = 1)
the error i get is: -
[Running] python -u "g:\Projects\Coding\Python\Folder files\xomtact book\main.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Sandeep Sharma\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "g:\Projects\Coding\Python\Folder files\xomtact book\main.py", line 63, in login_button_click
home.HomeWindow()
File "g:\Projects\Coding\Python\Folder files\xomtact book\home.py", line 38, in __init__
change_password_button = Button(navigation_frame, text= 'Change password', style= 'Navigation.TButton', command= self.change_password_button_click)
File "C:\Users\Sandeep Sharma\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 2383, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'change_password_button_click'
PLEASE HELP ME I'M STUCK WITH THIS PEICE OF CODE
BTW my name is Vedant
This error is coming because there is no such thing as self.change_password_button_click in your HomeWindow class. You have never created that function in your HomeWindow class.
The problem is here:
class HomeWindow:
def __init__(self)
def change_password_button_click(self): # Here is the error because this function should not be indented it should be something like this below:
def change_password_button_click(self): #This is where the function should be defined.
The problem is that you have the change password function inside the init function, so calling self.change_password_button_click makes the compiler think it should be outside the __init__ function.
If you want to have it indented then you should remove self as parameter in you change password function and call it as change_password_button_click(): Just another approach to solve your problem.
Hopefully this works for you. I don't have enough time to test your code. If it does work, you can tick this answer.
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()
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.
I have written a code for a basic game but the image and shape don't show up unless I add something like item.pack() or win.mainloop() [which doesn't really make sense] but then the lines below it don't run.
When I don't have anything, the buttons show up but the image doesn't show up.
import tkinter as tk
import random
from tkinter import messagebox
win = tk.Tk()
my_label = tk.Label(win, text="Color of the Baloon Game")
my_label.pack()
my_canvas = tk.Canvas(win, width=400, height=600)
my_canvas.pack()
background_image=tk.PhotoImage(file = "CS_Game_menu.png")
background_label = tk.Label(my_canvas, image=background_image)
background_label.photo = background_image
background_label.grid(row = 0, rowspan = 10, column = 0, columnspan = 10)
def drawCircle():
color = "green"
x1 = 265
y1 = 80
diameter = 90
my_canvas.destroy()
circle_button.destroy()
quit_button.destroy()
my_label.destroy()
my_label1 = tk.Label(win, text="What is the Color of the Baloon?", font="Purisa")
my_label1.pack()
my_canvas1 = tk.Canvas(win, width=400, height=600)
my_canvas1.pack()
image1 = r"CS_Game_baloon.png"
photo1 = tk.PhotoImage(file=image1)
item = my_canvas1.create_image(200, 350, image=photo1)
shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
item.pack()
game1_button = tk.Button(my_canvas1, text = "Green")
game1_button.grid(row= 8, column = 3)
game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
game2_button = tk.Button(my_canvas1, text = "Blue")
game2_button.grid(row= 8, column = 5)
game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
game3_button = tk.Button(my_canvas1, text = "Red")
game3_button.grid(row= 8, column = 7)
game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")
circle_button = tk.Button(win, text="New Game")
circle_button.pack()
circle_button["command"] = drawCircle
quit_button = tk.Button(win, text="Quit")
quit_button.pack()
quit_button['command'] = win.destroy
You are using both the create_... methods and grid methods on your canvas object. It won't behave as you expected.
To achieve what you want, you can create a Frame, put your buttons in it, and then use create_window method on your canvas:
def drawCircle():
...
shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
frame = tk.Frame(my_canvas1)
game1_button = tk.Button(frame, text = "Green")
game1_button.grid(row= 8, column = 3)
game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
game2_button = tk.Button(frame, text = "Blue")
game2_button.grid(row= 8, column = 5)
game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
game3_button = tk.Button(frame, text = "Red")
game3_button.grid(row= 8, column = 7)
game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")
my_canvas1.create_window(200,500,window=frame)
And of course, add win.mainloop() to the bottom of your program if you haven't already.