so when I was trying o make a game the front page is good
Front page
but when I tried the game no image is shown. why? how can it get to fix it without changing the system order?
it always shows no image or just nothing in my other projects don't know why
a screen shot
here code:
from Tkinter import *
from PIL import Image,ImageTk
from Winsound import *
win = Tk()
win.config(bg="#e300ff")
win.geometry("950x600+160+60")
win.resizable(width = False, height = False)
def play_sound_play():
global playgame
PlaySound("SoundEffects\Coins.wav", SND_FILENAME)
playbtn.destroy()
win.config(bg="white")
playgame = True
game()
def printpos(event):
print(f"{plr_posx}")
def MoveLeft(event):
global plr_posx
if plr_posx == 311:
print("cant go into grass")
else:
plr_posx -= 150
plr.place(x=plr_posx,y=plr_posy)
def MoveRight(event):
global plr_posx
if plr_posx >= 610:
print("cant go into grass")
else:
plr_posx += 150
plr.place(x=plr_posx,y=plr_posy)
def game():
global plr
global plr_posx
global plr_posy
#road
road_img = ImageTk.PhotoImage(Image.open("texture\ymd.png"))
road = Label(win, image=road_img)
road.pack()
road.place(x=321,y=0)
#grass
grass_img = ImageTk.PhotoImage(Image.open("texture\grass.png"))
grass1 = Label(win, image=grass_img)
grass1.pack()
grass1.place(x=-2,y=0)
grass2 = Label(win, image=grass_img)
grass2.pack()
grass2.place(x=646,y=0)
#Plr pos
plr_posx=311
plr_posy=450
#Plr
plr_img = ImageTk.PhotoImage(Image.open("texture\Player.png"))
plr = Label(win, image=plr_img)
plr.pack()
plr.place(x=plr_posx,y=plr_posy)
if playgame == False:
print("2")
else:
print("1")
#controls
win.bind("<Left>",MoveLeft)
win.bind("<Right>",MoveRight)
win.bind("<p>",printpos)
def main():
global playbtn
#PlayBtn
play_btn = ImageTk.PhotoImage(Image.open("texture\play_btn.png"))
playbtn = Button(win, image=play_btn,bd=0,bg="#e300ff",activebackground='#e300ff', command=play_sound_play)
playbtn.pack()
playbtn.place(x=150,y=250)
win.mainloop()
main()
no error is shown
No Error
even after I close it
no error
Related
I wanted to make a game like a clicker, where coding brings money, but I ran into this error. The error seems to be due to the fact that 'coding' is in another function, but I don't understand how I can fix it. Please help me. I will be very grateful to you
from tkinter import *
from time import sleep
from threading import *
from tkinter import ttk
from tkinter import messagebox
button_track = False
button_code = True
wait_code = 30
def check_code():
global button_code
if button_code == True:
money.set(money.get() + 50)
button_code = False
def buy_klava_func():
if money.get() >= 50:
money.set(money.get() - 50)
buy_klava.grid_remove()
coding = Button(root, text='Написать код', command=check_code)
coding.grid(column=0, row=0)
def timer_code():
global button_code
global wait_code
while True:
if button_code == False:
coding['state'] = 'disabled'
sleep(wait_code)
coding['state'] = 'active'
button_code = True
root = Tk()
root.geometry('900x900')
money = IntVar()
money.set(50)
buy_klava = Button(root, text='Купить клавиатуру (50 монет)', command=buy_klava_func)
buy_klava.grid(column=0, row=0)
th_timer_code = Thread(target=timer_code)
th_timer_code.start()
root.mainloop()
Looks like coding is not a global variable. Declare it above all the functions, so that you can use it within all functions.
from tkinter import *
from time import sleep
from threading import *
from tkinter import ttk
from tkinter import messagebox
button_track = False
button_code = True
wait_code = 30
def check_code():
global button_code
if button_code == True:
money.set(money.get() + 50)
button_code = False
def buy_klava_func():
global coding # <=== define coding as global
if money.get() >= 50:
money.set(money.get() - 50)
buy_klava.grid_remove()
coding = Button(root, text='Написать код', command=check_code)
coding.grid(column=0, row=0)
def timer_code():
global button_code
global wait_code
global coding
while True:
if button_code == False:
coding['state'] = 'disabled'
sleep(wait_code)
coding['state'] = 'active'
button_code = True
root = Tk()
root.geometry('900x900')
money = IntVar()
money.set(50)
buy_klava = Button(root, text='Купить клавиатуру (50 монет)', command=buy_klava_func)
buy_klava.grid(column=0, row=0)
th_timer_code = Thread(target=timer_code)
th_timer_code.start()
root.mainloop()
It is because coding is a local variable, so it cannot be accessed inside timer_code().
Since you just replace buy_klava by coding, my suggestion is simply to configure buy_klava instead of removing it and creating coding:
def buy_klava_func():
if money.get() >= 50:
money.set(money.get() - 50)
"""
buy_klava.grid_remove()
coding = Button(root, text='Написать код', command=check_code)
coding.grid(column=0, row=0)
"""
# just configure "buy_klava" instead of removing it and create "coding"
buy_klava.config(text='Написать код', command=check_code)
def timer_code():
global button_code
#global wait_code
while True:
if button_code == False:
buy_klava['state'] = 'disabled' # update buy_klava
sleep(wait_code)
buy_klava['state'] = 'active' # update buy_klava
button_code = True
Here, is my code snippet:
def message(name, button):
button['state'] = DISABLED
mgs_label = ttk.Label(root)
if button["text"] == "Encryption":
mgs_label.pack_forget()
mgs = encryption(name)
mgs_label = ttk.Label(root, text=mgs).pack(side=LEFT)
if button["text"] == "Decryption":
mgs_label.pack_forget()
mgs = decryption(name)
mgs_label = ttk.Label(root, text=mgs).pack(side=LEFT)
When i am click the button whether it is encryption button or decryption button it is comes at mentioned position.
Here is the snapshot :
image1
And When i am click the another button the text comes after the previous one, i want to remove the previous text and then the last mgs should be displayed.
second snapshot : image2
Even i tried to make global variables but then the problem is encryption or decryption is done but the mgs is not showing on the GUI here is the code for that :
encryption_label = ttk.Label(root)
decryption_label = ttk.Label(root)
def message(name, button):
button['state'] = DISABLED
global encryption_label, decryption_label
if button["text"] == "Encryption":
if decryption_label.winfo_exists():
decryption_label.pack_forget()
mgs = encryption(name)
encryption_label["text"] = mgs
encryption_label.pack(side=LEFT)
if button["text"] == "Decryption":
if encryption_label.winfo_exists():
encryption_label.pack_forget()
mgs = decryption(name)
decryption_label["text"] = mgs
decryption_label.pack(side=LEFT)
I suggest creating the label only once and use label.configure to change the text.
You should provide a working example instead of a code snippet. I made one for you.
Thank you for your question.
import tkinter as tk
from tkinter import ttk
def e():
message(None,x_button)
def d():
message(None,y_button)
def message(name, button):
#button['state'] = tk.DISABLED
if button["text"] == "Encryption":
mgs_label.configure(text = 'encrypted stuff')
if button["text"] == "Decryption":
mgs_label.configure(text = 'decrypted stuff')
root = tk.Tk()
x_button = tk.Button(root,text = 'Encryption',
command = e)
y_button = tk.Button(root,text = 'Decryption',
command = d )
mgs_label = ttk.Label(root)
y_button.pack()
x_button.pack()
mgs_label.pack()
root.mainloop()
I need to make this clock open only after pressing a key, lets say "t". Now it opens immediately after running it.
import tkinter as tk
def update_timeText():
if (state):
global timer
timer[2] += 1
if (timer[2] >= 100):
timer[2] = 0
timer[1] += 1
if (timer[1] >= 60):
timer[0] += 1
timer[1] = 0
timeString = pattern.format(timer[0], timer[1], timer[2])
timeText.configure(text=timeString)
root.after(10, update_timeText)
def start():
global state
state=True
state = False
root = tk.Tk()
root.wm_title('Simple Kitchen Timer Example')
timer = [0, 0, 0]
pattern = '{0:02d}:{1:02d}:{2:02d}'
timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
timeText.pack()
startButton = tk.Button(root, text='Start', command=start)
startButton.pack()
update_timeText()
root.mainloop()
It is in another program so as I have my graphics window I will press "t" and the clock will open.
Keyboard is a python module that can detect keystrokes. Install it by doing this command.
pip install keyboard
Now you can do this.
while True:
try:
if keyboard.is_pressed('t'):
state = True
elif(state != True):
pass
except:
state = False
break #a key other than t the loop will break
I would recommend you to organize the code little bit, like class structure. One possible implementation would be like that:
import tkinter as tk
TIMER = [0, 0, 0]
PATTERN = '{0:02d}:{1:02d}:{2:02d}'
class Timer:
def __init__(self, master):
#I init some variables
self.master = master
self.state = False
self.startButton = tk.Button(root, text='Start', command=lambda: self.start())
self.startButton.pack()
self.timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
self.timeText.pack()
def start(self):
self.state = True
self.update_timeText()
def update_timeText(self):
if (self.state):
global TIMER
TIMER[2] += 1
if (TIMER[2] >= 100):
TIMER[2] = 0
TIMER[1] += 1
if (TIMER[1] >= 60):
TIMER[0] += 1
TIMER[1] = 0
timeString = PATTERN.format(TIMER[0], TIMER[1], TIMER[2])
self.timeText.configure(text=timeString)
self.master.after(10, self.update_timeText)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("900x600")
root.title("Simple Kitchen Timer Example")
graph_class_object = Timer(master=root)
root.mainloop()
So clock will start when you click to button. If you want to start the clock by pressing "t" in keyboard, you need to bind that key to your function.
You can also add functionality if you want to stop the clock when you click to the button one more time.
EDIT:
if you also want to start to display the clock by clicking the button, you can move the code for initializing the label in to start function.
def start(self):
self.state = True
self.timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
self.timeText.pack()
self.update_timeText()
So i've been making a program for the past few days but there is this issue that I thought would be easy to fix, but turns out it wasnt so easy...
Here is my code:
print("Loading...")
from threading import *
from tkinter import *
import time
root = Tk()
root.title("Card Revealer BETA")
root.resizable(False, False)
image1 = PhotoImage(file="images\core\GUI.png")
w = image1.width()
h = image1.height()
root.geometry("%dx%d+0+0" % (w, h))
panel1 = Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')
Card1Image = PhotoImage(file="images\core\_blank.png")
Card1 = Label(panel1, image=Card1Image, width=80, height=100)
Card1.place(x=60, y=482)
Card2Image = PhotoImage(file="images\core\_blank.png")
Card2 = Label(panel1, image=Card2Image, width=80, height=100)
Card2.place(x=200, y=482)
Card3Image = PhotoImage(file="images\core\_blank.png")
Card3 = Label(panel1, image=Card3Image, width=80, height=100)
Card3.place(x=340, y=482)
Card4Image = PhotoImage(file="images\core\_blank.png")
Card4 = Label(panel1, image=Card4Image, width=80, height=100)
Card4.place(x=490, y=482)
Card5Image = PhotoImage(file="images\core\_blank.png")
Card5 = Label(panel1, image=Card5Image, width=80, height=100)
Card5.place(x=650, y=482)
from scapy.all import *
print("Finished loading.")
Deck = []
pick = None
picked = False
Side = ""
def PlaceCards(cards):
global Card1Image
global Card2Image
global Card3Image
global Card4Image
global Card5Image
Card1Image = PhotoImage(file="images\Cards\_%s.png"%(cards[0]))
Card2Image = PhotoImage(file="images\Cards\_%s.png"%(cards[1]))
Card3Image = PhotoImage(file="images\Cards\_%s.png"%(cards[2]))
Card4Image = PhotoImage(file="images\Cards\_%s.png"%(cards[3]))
Card5Image = PhotoImage(file="images\Cards\_%s.png"%(cards[4]))
def action(packet):
global Deck
global Side
global pick
global picked
global switchcount
c = 0
try:
if (packet[IP].src == "149.202.87.103"):
rawdata = packet.payload.payload.load
rawdata = str(rawdata)
if (rawdata[2:8] == "%xt%zm"):
if (IsOpponent(rawdata) == True):
if (IsDeck(rawdata) == True and picked == True):
rawdata = ClearFirstBit(rawdata)
NewCard = GetIDs(rawdata)
MoveUpdate(Deck[pick], NewCard)
print("Opponent New Deck:\n ", Deck)
picked == False
elif (IsDeck(rawdata) == True):
rawdata = ClearFirstBit(rawdata)
Deck = GetIDs(rawdata)
PlaceCards(Deck)
picked = True
print("Opponent Deck:\n ", Deck)
elif (IsPick(rawdata) == True):
pick = GetPick(rawdata)
print("Opponent chosen card:\n ", Deck[pick])
picked = True
if (rawdata[2:8] == "%xt%jz"):
setside(rawdata[2:])
print("Side detected: %s"%(Side))
except Exception as e:
print(e)
def sniffer():
sniff(prn=action)
sniffthread = Thread(target=sniffer)
sniffthread.daemon = True
sniffthread.start()
PlaceCards([1, 1, 1, 1, 1])
root.mainloop()
The program is supposed to sniff your internet and try to figure out card id's in a game this is for (its a game cheat). It is able to get all the card id's and put it into an array just fine, and I made a folder with all the card images named their id so that the program can easy put your card on the gui. It is able to locate the image just fine, but it appears as a white image for some reason, so if anyone knows why this is that would be very helpful! Also, the error is NOT the gui, the gui works just fine. The issue is with the PlaceCards function
I had the same problem. I solved it like this:
from PIL import Image, ImageTk
pathtophoto = Image.open("images\core\GUI.png")
image1 = ImageTk.PhotoImage(pathtophoto)
panel1 = Label(root, image=image1)
panel1.image = image1 #keep a reference
panel1.pack(side='top', fill='both', expand='yes')
You need to make sure that the pathtophoto is a line over root = Tk()
I hope this helps a little.
This is a simple math game which is currently in progress. The loop starts off in mainGame() which then proceeds to mainMenu(). I am trying to create 2 frames; mframe and gframe in order to .destroy() the frames later on, essentially clearing the previous interface for the next one (similar to changing pages).
error:
Label(gframe, textvariable=self.question_var).pack() #gframe stands
for game frame NameError: name 'gframe' is not defined
from tkinter import *
from random import randint
root = Tk()
mframe = Frame(root).pack()
gframe = Frame(root).pack()
frame.pack()
start = True
class mainMenu:
def __init__(self):
gframe.destroy() #gets rid of previous interface
title = Label(mframe, text = "main menu").pack() #mfame stands for menu frame
class mainGame:
def __init__(self):
if start == False:
mframe.destroy() #gets rid of previous interface
#question
self.question_var = StringVar()
Label(gframe, textvariable=self.question_var).pack() #gframe stands for game frame
#answer
self.user_answer_var = StringVar()
entry = Entry(gframe, textvariable=self.user_answer_var)
entry.pack()
submit = Button(gframe, text = "submit", command = self.check_answer).pack()
#response output
self.response_var = StringVar()
self.count = 0
self.score = 0
Label(gframe, textvariable=self.response_var).pack()
#starts loop
self.ask_question()
root.mainloop()
def ask_question(self):
if self.count == 1:
self.endGame()
num1 = randint(1, 10)
num2 = randint(1, 10)
self.question_var.set("What is "+str(num1)+" + " +str(num2)+"?")
self.true_answer = num1 + num2
#print(self.true_answer) #testing purposes
def check_answer(self):
self.count += 1
user_answer = self.user_answer_var.get()
#print(user_answer) #testing purposes
if int(user_answer) == self.true_answer:
text = "Good job"
self.score += 1
else:
text = "Oh no"
self.response_var.set(text)
#clear answer for next loop
self.user_answer_var.set("")
self.ask_question()
def endGame(self):
print("endGame")
mainMenu()
mainGame()
As said in the comments above, the pack() method returns None. What you need to do is first create the two frames and assign them to variables, then pack them later. This way, the variables still point to the frame instances and not None.
You should change;
root = Tk()
mframe = Frame(root).pack()
gframe = Frame(root).pack()
frame.pack()
start = True
to;
root = Tk()
mframe = Frame(root)
gframe = Frame(root)
mframe.pack()
gframe.pack()
start = True