im lost!
im trying to write a some sort of a blackjack game with a few changes from the original game.
if you notice in towards the end of the code i made a button named restart_button.
the function he calls is reset_game. when i try to run the code i get the error message - NameError: name 'reset_game' is not defined
do you guys have any idea of how do i fix it? thanks in advance
ps. i started coding like 2 months ago, so please dont get mad at my not so pretty code.
import random
from tkinter import *
window = Tk()
window.title("Black Jack (made by ziv)")
icon = PhotoImage(file='icon.png')
window.iconphoto(True, icon)
window.config(background='#696868')
window.geometry("670x600")
window.resizable(False, False)
player1_cards_total = 0
player2_cards_total = 0
main_label = Label(window, text='Player 1 Turn!', font=('Ariel', 40, 'bold'), fg='Black', bg="#696868")
player1_card_count_label = Label(window, text="Card Count: 0", font=('Ariel', 30, 'bold'), pady=30, fg='black', bg='#696868')
player2_card_count_label = Label(window, text="Card Count: 0", font=('Ariel', 30, 'bold'), pady=30, fg='black', bg='#696868')
def welcome_screen():
global welcome_label
global instruction_label
global rules_label
global move_to_instructions_button
global move_to_game_button
global move_to_welcome_button
label_remover()
welcome_label.grid(row=0, column=0, columnspan=2, sticky="e")
move_to_instructions_button.grid(row=1, column=0, padx=20)
move_to_game_button.grid(row=1, column=1)
def instructions_maker():
global welcome_label
global instruction_label
global rules_label
global move_to_instructions_button
global move_to_game_button
global move_to_welcome_button
label_remover()
instruction_label.grid(row=0, column=0, columnspan=2)
rules_label.grid(row=1, column=0, columnspan=2)
move_to_welcome_button.grid(row=2, column=0)
move_to_game_button.grid(row=2, column=1)
def main():
global instruction_label
global rules_label
global move_to_game_button
global move_to_welcome_button
global move_to_instructions_button
label_remover()
move_to_welcome_button.grid(row=4, column=0)
move_to_instructions_button.grid(row=4, column=1)
def player1_draw_card():
global player1_cards_total
player1_cards_total += random.randint(1, 13)
player1_card_count_label.config(text="Card Count: " + str(player1_cards_total))
if player1_cards_total == 21:
main_label.config(text="Player 2 Turn!")
player1_draw_card_button.config(state=DISABLED)
player1_999.config(state=DISABLED)
player2_draw_card_button.config(state=NORMAL)
player2_999.config(state=NORMAL)
if player1_cards_total > 21:
main_label.config(text="Player 2 Won!")
stop_game()
def player1_stop_play(p1_entry_input):
if player1_999.get()[len(player1_999.get()) - 1] != '9':
x = player1_999.get()
player1_999.delete(0, END)
player1_999.insert(0, x[0:len(x) - 1])
elif player1_999.get() == '999':
player1_draw_card_button.config(state=DISABLED)
player1_999.config(state=DISABLED)
player2_draw_card_button.config(state=NORMAL)
player2_999.config(state=NORMAL)
main_label.config(text="Player 2 Turn!")
def player2_draw_card():
global player1_cards_total
global player2_cards_total
player2_cards_total += random.randint(1, 13)
player2_card_count_label.config(text="Card Count: " + str(player2_cards_total))
if player1_cards_total < player2_cards_total <= 21:
main_label.config(text="Player 2 Won!")
player1_draw_card_button.config(state=DISABLED)
player1_999.config(state=DISABLED)
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=DISABLED)
stop_game()
elif player1_cards_total == player2_cards_total == 21:
main_label.config(text="Draw! Lets Reset!")
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=DISABLED)
window.after(2500, reset_game)
elif player2_cards_total > 21:
main_label.config(text="Player 1 Won!")
stop_game()
def player2_stop_play(p2_entry_input):
if player2_999.get()[len(player2_999.get()) - 1] != '9':
x = player2_999.get()
player2_999.delete(0, END)
player2_999.insert(0, x[0:len(x) - 1])
elif player2_999.get() == '999':
global player1_cards_total
global player2_cards_total
if player1_cards_total < player2_cards_total <= 21:
main_label.config(text="Player 2 Won!")
player1_draw_card_button.config(state=DISABLED)
player1_999.config(state=DISABLED)
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=DISABLED)
stop_game()
restart_button.grid(row=5, column=0, columnspan=2, pady=10)
elif player1_cards_total == player2_cards_total and player2_cards_total <= 21:
main_label.config(text="Draw! Lets Reset!")
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=DISABLED)
window.after(3500, reset_game)
elif player2_cards_total < player1_cards_total <= 21:
main_label.config(text="Player 1 Won!")
stop_game()
def reset_game():
global player1_cards_total
global player2_cards_total
main_label.config(text="Player 1 Turn")
player1_cards_total = 0
player2_cards_total = 0
player1_card_count_label.config(text="Card Count: " + str(player1_cards_total))
player2_card_count_label.config(text="Card Count: " + str(player2_cards_total))
player1_draw_card_button.config(state=NORMAL)
player1_999.config(state=NORMAL)
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=NORMAL)
player1_999.delete(0, END)
player2_999.delete(0, END)
player2_999.config(state=DISABLED)
try:
restart_button.grid_remove()
except:
pass
def stop_game():
global player1_cards_total
global player2_cards_total
global restart_button
player1_draw_card_button.config(state=DISABLED)
player1_999.config(state=DISABLED)
player2_draw_card_button.config(state=DISABLED)
player2_999.config(state=DISABLED)
restart_button.grid(row=5, column=0, columnspan=2, pady=10)
player1_draw_card_button = Button(text="player 1" + "\n" + "draw card", padx=80, pady=50, bg="#212121", fg="#FFFFFF",
command=player1_draw_card, font=('Ariel', 20, 'bold'), state=NORMAL)
player2_draw_card_button = Button(text="player 2" + "\n" + "draw card", padx=80, pady=50, bg="#212121", fg="#FFFFFF",
command=player2_draw_card, font=('Ariel', 20, 'bold'), state=DISABLED)
player1_999 = Entry(window, state=NORMAL, font=('Ariel', 30, 'bold'), width=5, fg='black', bg='#3b3b3b',
disabledbackground='#212121', disabledforeground='black')
player2_999 = Entry(window, state=DISABLED, font=('Ariel', 30, 'bold'), width=5, fg='black', bg='#3b3b3b',
disabledbackground='#212121', disabledforeground='black')
player1_999.bind("<KeyRelease>", player1_stop_play)
player2_999.bind("<KeyRelease>", player2_stop_play)
main_label.grid(row=0, column=0, columnspan=2)
player1_card_count_label.grid(row=1, column=0)
player1_draw_card_button.grid(row=2, column=0, padx=10)
player1_999.grid(row=3, column=0, pady=20, ipadx=30)
player2_card_count_label.grid(row=1, column=1)
player2_draw_card_button.grid(row=2, column=1, padx=10)
player2_999.grid(row=3, column=1, pady=20, ipadx=30)
def label_remover():
welcome_label.grid_remove()
instruction_label.grid_remove()
rules_label.grid_remove()
move_to_instructions_button.grid_remove()
move_to_game_button.grid_remove()
move_to_welcome_button.grid_remove()
main_label.grid_remove()
player1_card_count_label.grid_remove()
player2_card_count_label.grid_remove()
welcome_label = Label(window, text=" welcome to my Black Jack game!" + "\n" + " made by ziv lahav",
font=('Ariel', 20, 'bold'), pady=30, fg='black', bg='#696868')
move_to_instructions_button = Button(text='instructions screen', width=20, height=5, bg="#212121", fg="#FFFFFF",
command=instructions_maker, font=('Ariel', 12, 'bold'), state=NORMAL)
move_to_game_button = Button(text='start game', width=20, height=5, bg="#212121", fg="#FFFFFF", command=main,
font=('Ariel', 12, 'bold'), state=NORMAL)
instruction_label = Label(window, text=" instructions:\n the player draws cards valued at 1-13. \n"
" when the player wants to switch turns,\n he writes '999' in the input box.",
font=('Ariel', 20, 'bold'), pady=30, fg='black', bg='#696868')
rules_label = Label(window, text=" goal:\n the goal is to get as close as you get to 21.\n"
" if a player's total card count > 21, he looses", font=('Ariel', 20, 'bold'), pady=30,
fg='black', bg='#696868')
move_to_welcome_button = Button(text="welcome screen", width=20, height=5, bg="#212121", fg="#FFFFFF", command=welcome_screen,
font=('Ariel', 12, 'bold'), state=NORMAL)
restart_button = Button(text="Click Here To Restart", width=20, height=5, bg="#212121", fg="#FFFFFF", command=reset_game,
font=('Ariel', 9, 'bold'), state=NORMAL)
welcome_screen()
window.mainloop()
restart_button can't see inside main(). You have a bunch of functions defined within the main() function for some reason, including reset_game, and so anything that's not in the scope of main() can't see those functions. The solution is to move the functions outside of main().
#RandomDavis gave a good answer, what I can suggest is, you can work in a class. Make a main class and than add other functions inside it. It may work that way!
Related
I am recreating the game Wordle for practice.
I am trying to find a function that allows me to destroy all widgets in my tkinter window.
root.destroy() isn't a solution because it just closes the whole window.
I want to use this function to, whenever we win the game, restart the whole program without having to manually do it.
Program:
from tkinter import *
from tkinter import ttk
import tkinter as tk
from english_words import english_words_alpha_set
import time
guess = "bored"
guess = guess.upper()
word=""
a=0
def callback1(var, index, mode):
root.entry2.configure(state="normal")
root.entry2.focus()
root.entry1.configure(state="disabled")
root.hasfocus = "entry2"
def callback2(var, index, mode):
root.entry3.configure(state="normal")
root.entry3.focus()
root.entry2.configure(state="disabled")
root.hasfocus = "entry3"
def callback3(var, index, mode):
root.entry4.configure(state="normal")
root.entry4.focus()
root.entry3.configure(state="disabled")
root.hasfocus = "entry4"
def callback4(var, index, mode):
root.entry5.configure(state="normal")
root.entry5.focus()
root.entry4.configure(state="disabled")
root.hasfocus = "entry5"
def callback5(var, index, mode):
root.entry5.configure(state="disabled")
root.hasfocus = "none"
def newRow():
boxes = [root.box1, root.box2, root.box3, root.box4, root.box5]
word = root.name1.get() + root.name2.get() + root.name3.get() + root.name4.get() + root.name5.get()
word=word.upper()
root.greenBoxes=0
def checkBg():
if word[a] == guess[a]:
root.greenBoxes=root.greenBoxes+1
print("greenBoxes=", root.greenBoxes)
return '#538D4E'
elif word[a] in guess:
return '#B59F3B'
else:
return '#3A3A3C'
root.entry1.destroy()
root.entry2.destroy()
root.entry3.destroy()
root.entry4.destroy()
root.entry5.destroy()
a=0
while a < 5:
boxes[a].configure(text=word[a], bg=checkBg(), fg = "white")
a=a+1
if root.greenBoxes == 5: #if player won:
root.WinMsg = Label(root, height=2, width=28, bg='#2d2d2f', fg='white', text='You\'ve won! The word was \"' + guess[0] + guess[1:5].lower() +"\"", font="Calibri 20")
root.WinMsg.place(x=65, y=100) #say that he won
#*destroy all widgets*
root.CreateWindow() #remake all widgets (to start a new game)
return
root.rows = root.rows+1
if root.rows < 6: #if player still have any try
root.d=root.d+70
root.createBoxes()
root.createEntry()
else: #if player lost
root.GameOverMsg = Label(root, height=2, width=28, bg='#2d2d2f', fg='white', text='You\'ve lost! The word was \"' + guess[0] + guess[1:5].lower() +"\"", font="Calibri 20")
root.GameOverMsg.place(x=65, y=100) #says that he lost
#*destroy all widgets*
root.CreateWindow() #remake all widgets (to start a new game)
return
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.title("Wordle")
self.minsize(580,465)
self.windowBG = '#121213'
self.CreateWindow()
def CreateWindow(self):
self.configure(bg=self.windowBG)
self.hasfocus = ""
self.d=0
self.rows=0
self.greenBoxes = 0
self.createBoxes()
self.createEntry()
self.backspace = Button(self, text="Backspace", width=8, font ="Calibri 18", command=self.do_backspace)
self.backspace.place(x=465, y=62)
self.enter = Button(self, text="Enter", width=6, font ="Calibri 18", command=self.do_enter)
self.enter.place(x=480, y=125)
def createBoxes(self):
self.box1 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box1.place(x=70, y=30+self.d)
self.box2 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box2.place(x=150, y=30+self.d)
self.box3 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box3.place(x=230, y=30+self.d)
self.box4 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box4.place(x=310, y=30+self.d)
self.box5 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box5.place(x=390, y=30+self.d)
def do_backspace(self):
if self.hasfocus == "entry1":
pass
elif self.hasfocus == "entry2":
self.entry1.configure(state="normal")
self.entry1.delete(0, 'end')
self.entry1.configure(state="normal")
self.entry1.focus()
self.hasfocus="entry1"
self.entry2.configure(state="disabled")
elif self.hasfocus == "entry3":
self.entry2.configure(state="normal")
self.entry2.delete(0, 'end')
self.entry2.configure(state="normal")
self.entry2.focus()
self.hasfocus="entry2"
self.entry3.configure(state="disabled")
elif self.hasfocus == "entry4":
self.entry3.configure(state="normal")
self.entry3.delete(0, 'end')
self.entry3.configure(state="normal")
self.entry3.focus()
self.hasfocus="entry3"
self.entry4.configure(state="disabled")
elif self.hasfocus == "entry5":
self.entry4.configure(state="normal")
self.entry4.delete(0, 'end')
self.entry4.configure(state="normal")
self.entry4.focus()
self.hasfocus="entry4"
self.entry5.configure(state="disabled")
else:
self.entry5.configure(state="normal")
self.entry5.delete(0, 'end')
self.entry5.configure(state="normal")
self.entry5.focus()
self.hasfocus="entry5"
def do_enter(self):
if len(self.name1.get() + self.name2.get() + self.name3.get() + self.name4.get() + self.name5.get()) == 5:
newRow()
else:
self.FiveLetterWord = Label(self, height=2, width=22, bg='#2d2d2f', fg='white', text='Word must be of 5 letters', font="Calibri 20", background=self.windowBG,highlightbackground='#3A3A3C', highlightthickness=2)
self.FiveLetterWord.place(x=100, y=100)
self.update_idletasks()
self.after(3000)
self.FiveLetterWord.destroy()
def createEntry(self):
self.name1 = StringVar()
self.entry1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15", justify='center')
self.entry1.place(x=90, y=40+self.d)
self.name2 = StringVar()
self.entry2 = ttk.Entry(self, width=2, textvariable = self.name2, font="Calibri 15", justify='center')
self.entry2.place(x=170, y=40+self.d)
self.entry2.configure(state="disabled")
self.name3 = StringVar()
self.entry3 = ttk.Entry(self, width=2, textvariable = self.name3, font="Calibri 15", justify='center')
self.entry3.place(x=250, y=40+self.d)
self.entry3.configure(state="disabled")
self.name4 = StringVar()
self.entry4 = ttk.Entry(self, width=2, textvariable = self.name4, font="Calibri 15", justify='center')
self.entry4.place(x=330, y=40+self.d)
self.entry4.configure(state="disabled")
self.name5 = StringVar()
self.entry5 = ttk.Entry(self, width=2, textvariable = self.name5, font="Calibri 15", justify='center')
self.entry5.place(x=410, y=40+self.d)
self.entry5.configure(state="disabled")
self.entry1.focus() ; hasfocus = "entry1"
self.name1.trace_add("write", callback1)
self.name2.trace_add("write", callback2)
self.name3.trace_add("write", callback3)
self.name4.trace_add("write", callback4)
self.name5.trace_add("write", callback5)
root=root()
root.mainloop()
You can use winfo_children to get a list of all child widgets of the root window, and then you can iterate over the list to destroy each child.
for child in root.winfo_children():
child.destroy()
From that point on, you have a root window with nothing in it.
I'm trying to insert new lines of codes in the same running module every time the user input something. I tried with open function but this function in exe program will open a new file to write the user input in it and that will not help me. basically, I want user input to be added as a line of code in the same module that the application is running on. "note: Addingpage is another module that I use to add user input in it" here is my application:
` def addingfunction(self):
Name = self.name_add.get()
Email = self.email_add.get()
Password = self.passowrd_add.get()
if " " in Name:
self.name_fill_error = Label(self.adding_frame, text= "Name shouldn't have a space", fg='red', bg='white', font=('merriweather', 10, 'bold'))
self.name_fill_error.grid(row=11, column=1, sticky='w')
self.adding_frame.after(2000, self.name_fill_error.grid_remove)
elif Name == "" or Email == "" or Password == "":
self.name_fill_error = Label(self.adding_frame, text='Data is empty', fg='red', bg='white', font=('merriweather', 10, 'bold'))
self.name_fill_error.grid(row=11, column=1, sticky='w')
self.adding_frame.after(2000, self.name_fill_error.grid_remove)
elif Name in Addingpage.accountslist:
self.name_fill_error = Label(self.adding_frame, text='Account name already exist', fg='red', bg='white', font=('merriweather', 10, 'bold'))
self.name_fill_error.grid(row=11, column=1, sticky='w')
self.adding_frame.after(2000, self.name_fill_error.grid_remove)
else:
self.x += 1
with open("Addingpage.py", 'a') as A:
A.write(f" self.e{Name} = Frame(self.bigframe_1, bg='white')\n")
A.write(
f" Label(self.e{Name}, text='Account Name: {Name}', font=('merriweather', 10, 'bold'), bg='white', fg='blue').pack(anchor=W)\n")
A.write(
f" Label(self.e{Name}, text='Email: {Email}', font=('merriweather', 10, 'bold'), bg='white', fg='black').pack(anchor=W)\n")
A.write(
f" Label(self.e{Name}, text='Password: {Password}', font=('merriweather', 10, 'bold'), bg='white', fg='black').pack(anchor=W)\n")
A.write(
f" Label(self.e{Name}, text='', font=('merriweather', 10, 'bold'), bg='white', fg='red').pack(anchor=W)\n")
A.write(f" if '{Name}' in accountslist:\n pass\n else:\n accountslist.append('{Name}')\n self.e{Name}.pack(anchor=W)\n")
self.clearingfunction()
self.account_added = Label(self.adding_frame, text='Your account is added', fg='green', bg='white',
font=('merriweather', 10, 'bold'))
self.account_added.grid(row=11, column=1, sticky='w')
self.adding_frame.after(2000, self.account_added.grid_remove)
def addingpage(self):
self.name_add = StringVar()
self.email_add = StringVar()
self.passowrd_add = StringVar()
self.removeall()
self.adding_frame = Frame(self.root, bg='white')
self.welcome = Label(self.adding_frame, text='', width=15, bg='white').grid(row=0, rowspan=5, column=0)
self.icongrid = Label(self.adding_frame, image=self.icon, bg='black', fg='white').grid(row=0, column=1)
'''Name box'''
Label(self.adding_frame, text='Name: ', bg='white', fg='black', font=('merriweather', 10, 'bold')).grid(row=6, column=0, sticky='e')
self.name_add = Entry(self.adding_frame, font=('merriweather', 10, 'bold'), fg='blue', bg='gray', width=16)
self.name_add.grid(row=6, column=1, sticky='w')
'''Email box'''
Label(self.adding_frame, text='E-mail: ', bg='white', fg='black', font=('merriweather', 10, 'bold')).grid(row=7, column=0, sticky='e')
self.email_add = Entry(self.adding_frame, font=('merriweather', 10, 'bold'), fg='blue', bg='gray', width=32)
self.email_add.grid(row=7, column=1)
'''Password box'''
Label(self.adding_frame, text='Password: ', bg='white', fg='black', font=('merriweather', 10, 'bold')).grid(row=8, column=0, sticky='e')
self.passowrd_add = Entry(self.adding_frame, font=('merriweather', 10, 'bold'), fg='blue', bg='gray', width=32)
self.passowrd_add.grid(row=8, column=1)
'''Add button'''
add_button_adding = Button(self.adding_frame, text='Add', fg='white', font=('merriweather', 9, 'bold'), bg='black', activeforeground='green', width=20, command= self.addingfunction).grid(row=9, column=1)
'''Back to menu button'''
self.back_to_menu = Button(self.adding_frame, text='Back to menu', font=('merriweather', 9, 'bold'), command=self.mainmenu, fg='white', bg='black', width=10).grid(row=10, column=1)
self.adding_frame.grid(row=0, column=0)
`
I used in the end SQLite database where I store information and retrieve them from there, I tried JSON file but it is not good for my purpose, even SQLite I had to manipulate and play around with it in order to make it function as I want. Here is the code at the end.
for i in range(1, 1000):
c.execute(f"SELECT name FROM data WHERE id='{i}'")
name = str(c.fetchone())
end_slice = slice(-3)
Name = name[end_slice][2:]
c.execute(f"SELECT email FROM data WHERE id='{i}'")
email = str(c.fetchone())
Email = email[end_slice][2:]
c.execute(f"SELECT password FROM data WHERE id='{i}'")
password = str(c.fetchone())
Password = password[end_slice][2:]
if Name == "":
continue
Label(self.bigframe_1, text=f'Account Name: {Name}', font=('merriweather', 10, 'bold'), bg='white',
fg='blue').pack(anchor=W)
Label(self.bigframe_1, text=f'Email: {Email}', font=('merriweather', 10, 'bold'),
bg='white', fg='black').pack(anchor=W)
Label(self.bigframe_1, text=f'Password: {Password}', font=('merriweather', 10, 'bold'), bg='white',
fg='black').pack(anchor=W)
Label(self.bigframe_1, text='', font=('merriweather', 10, 'bold'), bg='white', fg='red').pack(anchor=W)
I have the following scraper:
I want to do an action to import the links when I click the button that corresponds to each one.
def ListarPeliculas(win, canvas, box_formulario, paginacion):
canvas.config(bg='#CCC')
#canvas.pack(side=LEFT, pady=20)
canvas.pack(side=LEFT, pady=20)
global scrollbar
scrollbar = Scrollbar(win, command=canvas.yview)
scrollbar.config(bg='#CCC')
scrollbar.pack(side=LEFT, pady=20, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
def on_configure(event):
canvas.configure(scrollregion=canvas.bbox('all'))
canvas.bind('<Configure>', on_configure)
box_formulario.config(bg='#CCC', padx=40)
canvas.create_window((0, 0), window=box_formulario, anchor='n')
url = 'https://divxtotal7.com/peliculas/page/'+paginacion.get()
header = var.user_agent
r = requests.get(url, headers=header)
soup = html.fromstring(r.text)
links_posts = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="meta"]/a/#href')
titulos_posts = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="meta"]/a/text()')
idiomas = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="imagen"]//img[#class="lazy"]/#src')
row = 1
count = 0
for link_post, titulo_post, idioma in zip(links_posts, titulos_posts, idiomas):
if idioma == '/images/espanolEspañol.png' or idioma == '/images/espanolEspanol.png':
idioma = 'Español España'
elif idioma == '/images/espanolVOSE.png':
idioma = 'Subtitulado a español'
elif idioma == '/images/espanolEspanol Latino.png':
idioma = 'Español Latino'
numero = Label(box_formulario, text=str(row))
numero.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
numero.grid(row=row, column=0, sticky='nw')
#name_peliculas = Label(box_formulario, text=titulo_post)
#name_peliculas.config(bg='#CCC', fg='black', font=('Arial', 8), pady=5)
#name_peliculas.grid(row=row, column=1, sticky='n')
peliculas_listada = Label(box_formulario, text=link_post, textvariable=link_post)
peliculas_listada.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
peliculas_listada.grid(row=row, column=1, sticky='n', columnspan=2, padx=60)
idioma_listada = Label(box_formulario, text=idioma)
idioma_listada.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
idioma_listada.grid(row=row, column=3, sticky='nw')
importar = Button(box_formulario, text='Importar', command=lambda: [print(link_post)])
importar.config(bg='orange', font=('Arial', 10, 'bold'))
importar.grid(row=row, column=4, sticky='e', padx=25, pady=5)
count += 1
row += 1
but when I get the link I get the last link and not what corresponds to each one
What I get every time I click on any button is the following link, the same one and not the one that corresponds to each one
https://divxtotal7.com/descargar/43813/padre,-soldado,-hijo/
https://divxtotal7.com/descargar/43813/padre,-soldado,-hijo/
thanks to the user the solution was this
def ListarPeliculas(win, canvas, box_formulario, paginacion):
canvas.config(bg='#CCC')
#canvas.pack(side=LEFT, pady=20)
canvas.pack(side=LEFT, pady=20)
global scrollbar
scrollbar = Scrollbar(win, command=canvas.yview)
scrollbar.config(bg='#CCC')
scrollbar.pack(side=LEFT, pady=20, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
def on_configure(event):
canvas.configure(scrollregion=canvas.bbox('all'))
canvas.bind('<Configure>', on_configure)
box_formulario.config(bg='#CCC', padx=40)
canvas.create_window((0, 0), window=box_formulario, anchor='n')
url = 'https://divxtotal7.com/peliculas/page/'+paginacion.get()
header = var.user_agent
r = requests.get(url, headers=header)
soup = html.fromstring(r.text)
links_posts = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="meta"]/a/#href')
titulos_posts = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="meta"]/a/text()')
idiomas = soup.xpath('//ul[#class="miniboxs miniboxs-ficha"]//div[#class="imagen"]//img[#class="lazy"]/#src')
row = 1
count = 0
for link_post, titulo_post, idioma in zip(links_posts, titulos_posts, idiomas):
if idioma == '/images/espanolEspañol.png' or idioma == '/images/espanolEspanol.png':
idioma = 'Español España'
elif idioma == '/images/espanolVOSE.png':
idioma = 'Subtitulado a español'
elif idioma == '/images/espanolEspanol Latino.png':
idioma = 'Español Latino'
numero = Label(box_formulario, text=str(row))
numero.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
numero.grid(row=row, column=0, sticky='nw')
#name_peliculas = Label(box_formulario, text=titulo_post)
#name_peliculas.config(bg='#CCC', fg='black', font=('Arial', 8), pady=5)
#name_peliculas.grid(row=row, column=1, sticky='n')
peliculas_listada = Label(box_formulario, text=link_post, textvariable=link_post)
peliculas_listada.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
peliculas_listada.grid(row=row, column=1, sticky='n', columnspan=2, padx=60)
idioma_listada = Label(box_formulario, text=idioma)
idioma_listada.config(bg='#CCC', fg='black', font=('Arial', 10), pady=5)
idioma_listada.grid(row=row, column=3, sticky='nw')
importar = Button(box_formulario, text='Importar', command=lambda link=link_post: print(link))
importar.config(bg='orange', font=('Arial', 10, 'bold'))
importar.grid(row=row, column=4, sticky='e', padx=25, pady=5)
count += 1
row += 1
In this practice program, I have created a Color Game. In this I have created a Button called Start Game. Game should start only after I press Start Game button. This button also disappears when game starts. It works perfectly first time. But when countdown gets over or when the player lose, Start Game button should reappear in same place. Start Button is reappearing, but it is calling the function as it should be. please anyone help?
from tkinter import *
from random import *
doc = open("Highscore.txt", "r")
us = 0
hs = int(doc.read())
time_count = 5
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
def add_uscore():
global us
us+= 1
score.config(text=(f"Score: {us}"))
def add_highscore():
global us
global hs
if us>hs:
hs = us
highscore.config(text=(f"Highscore: {hs}"))
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
def start_game():
global colorlist
global textcolor
rancolor = choice(colorlist)
textcolor = choice(colorlist)
start_btn.grid_forget()
color.config(text=rancolor, fg=textcolor)
btn1.config(state=ACTIVE, bg="Indian Red")
btn2.config(state=ACTIVE, bg="Gold")
btn3.config(state=ACTIVE, bg="DodgerBlue3")
btn4.config(state=ACTIVE, bg="Sea Green")
btn5.config(state=ACTIVE, bg="Dark Orange")
btn6.config(state=ACTIVE, bg="Purple3")
timer.grid(row=4, column=0, columnspan=3)
def countdown():
global time_count
if time_count > 0:
time_count -= 1
timer.config(text=(f"Countdown: {time_count}"))
timer.after(1000, countdown)
elif time_count==0:
result.config(text="Time Over", fg="Indian Red")
finish_game()
def finish_game():
timer.grid_forget()
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
def new_game():
global us
us = 0
score.config(text=(f"Score: {us}"))
finish_game()
def reset_game():
global hs
hs = 0
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
new_game()
def check(ucolor):
global textcolor
global time_count
if textcolor==ucolor:
result.config(text="Good", fg="Sea Green")
add_uscore()
add_highscore()
start_game()
time_count = 5
else:
result.config(text="You Lose", fg="Indian Red")
finish_game()
win = Tk()
win.title("Color Game")
#MENU
menu1 = Menu(win)
win.config(menu=menu1)
options = Menu(menu1)
menu1.add_cascade(label="Option", menu=options)
options.add_command(label="New Game", command=new_game)
options.add_command(label="Reset Game", command=reset_game)
options.add_command(label="Exit Game", command=quit)
#DISPLAY
color = Label(win, text="", font=("Comic Sans", 50), anchor=W)
color.grid(row=0, column=0, columnspan=4)
#BUTTON
btn1 = Button(win, text="Red", height=10, width=10, state=DISABLED, command=lambda:check("Red"))
btn1.grid(row=1, column=0)
btn2 = Button(win, text="Yellow", height=10, width=10,state=DISABLED, command=lambda:check("Yellow"))
btn2.grid(row=1, column=1)
btn3 = Button(win, text="Blue", height=10, width=10, state=DISABLED, command=lambda:check("Blue"))
btn3.grid(row=1, column=2)
btn4 = Button(win, text="Green", height=10, width=10, state=DISABLED, command=lambda:check("Green"))
btn4.grid(row=2, column=0)
btn5 = Button(win, text="Orange", height=10, width=10, state=DISABLED, command=lambda:check("Orange"))
btn5.grid(row=2, column=1)
btn6 = Button(win, text="Purple", height=10, width=10, state=DISABLED, command=lambda:check("Purple"))
btn6.grid(row=2, column=2)
#RESULT
result = Label(win, text="", font=("Ariel", 25))
result.grid(row=3, column=0, columnspan=3)
#COUNTDOWN
timer = Label(win, text="", fg="Dark Orange", font=("Ariel", 15))
#START BUTTON
start_btn = Button(win, text="START GAME", bg="Green", command= lambda: [start_game(), countdown()])
start_btn.grid(row=4, column=0, columnspan=3)
#SCORE
score = Label(win, text=(f"Score: {us}"), fg="Sea Green", font=("Ariel", 10))
score.grid(row=5, column=0, columnspan=3)
#HIGHSCORE
highscore = Label(win, text=(f"Highscore: {hs}"), font=("Ariel", 10), fg="firebrick4")
highscore.grid(row=6, column=0, columnspan=3)
win.mainloop()
In your code there is a variable time_count
It is set as 5 in the beginning of the code
...
hs = int(doc.read())
time_count = 5 # <-----------
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
...
When you run out of time, time_count has a value of 0. When you call the start_game function again, it sees that time_count is 0 and so the game must be over. To fix this, you'd have to reset time_count after each time the game ends. Something like this worked for me:
def finish_game():
global time_sleep
time_sleep = 5
timer.grid_forget()
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
Edit:
I managed to fix the countdown function executing on its own in the background by adding a gameover variable. When the game ends, it is set to 1, when the game starts it is again set to 0. The countdown function checks gameover and only executes when it is set to 0.
I also made the result label only appear when the game is over.
The full code:
from tkinter import *
from random import *
doc = open("Highscore.txt", "r")
us = 0
hs = int(doc.read())
time_count = 5
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
def add_uscore():
global us
us+= 1
score.config(text=(f"Score: {us}"))
def add_highscore():
global us
global hs
if us>hs:
hs = us
highscore.config(text=(f"Highscore: {hs}"))
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
def start_game():
global gameover
global colorlist
global textcolor
gameover = 0
rancolor = choice(colorlist)
textcolor = choice(colorlist)
start_btn.grid_forget()
result.grid_forget()
color.config(text=rancolor, fg=textcolor)
btn1.config(state=ACTIVE, bg="Indian Red")
btn2.config(state=ACTIVE, bg="Gold")
btn3.config(state=ACTIVE, bg="DodgerBlue3")
btn4.config(state=ACTIVE, bg="Sea Green")
btn5.config(state=ACTIVE, bg="Dark Orange")
btn6.config(state=ACTIVE, bg="Purple3")
timer.grid(row=4, column=0, columnspan=3)
def countdown():
global time_count
if time_count > 0 and gameover != 1:
time_count -= 1
timer.config(text=(f"Countdown: {time_count}"))
timer.after(1000, countdown)
elif time_count==0:
result.config(text="Time Over", fg="Indian Red")
finish_game()
def finish_game():
global time_count
time_count = 5
timer.grid_forget()
result.grid(row=3, column=0, columnspan=3)
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
def new_game():
global us
us = 0
score.config(text=(f"Score: {us}"))
finish_game()
def reset_game():
global hs
hs = 0
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
new_game()
def check(ucolor):
global textcolor
global time_count
global gameover
if textcolor==ucolor:
result.config(text="Good", fg="Sea Green")
add_uscore()
add_highscore()
start_game()
time_count = 5
else:
result.config(text="You Lose", fg="Indian Red")
gameover = 1
finish_game()
win = Tk()
win.title("Color Game")
#MENU
menu1 = Menu(win)
win.config(menu=menu1)
options = Menu(menu1)
menu1.add_cascade(label="Option", menu=options)
options.add_command(label="New Game", command=new_game)
options.add_command(label="Reset Game", command=reset_game)
options.add_command(label="Exit Game", command=quit)
#DISPLAY
color = Label(win, text="", font=("Comic Sans", 50), anchor=W)
color.grid(row=0, column=0, columnspan=4)
#BUTTON
btn1 = Button(win, text="Red", height=10, width=10, state=DISABLED, command=lambda:check("Red"))
btn1.grid(row=1, column=0)
btn2 = Button(win, text="Yellow", height=10, width=10,state=DISABLED, command=lambda:check("Yellow"))
btn2.grid(row=1, column=1)
btn3 = Button(win, text="Blue", height=10, width=10, state=DISABLED, command=lambda:check("Blue"))
btn3.grid(row=1, column=2)
btn4 = Button(win, text="Green", height=10, width=10, state=DISABLED, command=lambda:check("Green"))
btn4.grid(row=2, column=0)
btn5 = Button(win, text="Orange", height=10, width=10, state=DISABLED, command=lambda:check("Orange"))
btn5.grid(row=2, column=1)
btn6 = Button(win, text="Purple", height=10, width=10, state=DISABLED, command=lambda:check("Purple"))
btn6.grid(row=2, column=2)
#RESULT
result = Label(win, text="", font=("Ariel", 25))
#COUNTDOWN
timer = Label(win, text="", fg="Dark Orange", font=("Ariel", 15))
#START BUTTON
start_btn = Button(win, text="START GAME", bg="Green", command= lambda: [start_game(), countdown()])
start_btn.grid(row=4, column=0, columnspan=3)
#SCORE
score = Label(win, text=(f"Score: {us}"), fg="Sea Green", font=("Ariel", 10))
score.grid(row=5, column=0, columnspan=3)
#HIGHSCORE
highscore = Label(win, text=(f"Highscore: {hs}"), font=("Ariel", 10), fg="firebrick4")
highscore.grid(row=6, column=0, columnspan=3)
win.mainloop()
Notice how the result label is only placed with the grid manager when the game ends and it is removed once the game starts again:
Placing the result label with .grid when the game ends
def finish_game():
...
result.grid(row=3, column=0, columnspan=3)
...
Removing the result label with .grid_forget when the game starts
def start_game():
...
result.grid_forget()
...
So I am trying to each time you click one of the buttons that doesn't have the bomb, for the variable "score" to update and immediately being displayed on the bottom. But when I click one of them, the displayed variable is not updated for some reason even though I explicitly said for the "Label" being displayed to have the "text=score". I know my code is quite long and not really efficient but I am a bit new to python and I'm still learning. What could I fix in my code to solve this issue? ANY help is appreciated!
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
score = 0
def test():
ticket1 = random.randint(1,3)
ticket2 = random.randint(1,3)
def test1():
if ticket1 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=1, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=1, column=0, sticky="w")
global score
score += 1
def test2():
if ticket1 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=1, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=1, column=1, sticky="w")
global score
score += 1
def test3():
if ticket1 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=1, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=1, column=2, sticky="w")
global score
score += 1
def test4():
if ticket2 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
global score
score += 2
def test5():
if ticket2 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
global score
score += 2
def test6():
if ticket2 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
global score
score += 2
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button3 = 3
button4 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button4 = 1
button5 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button5 = 2
button6 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
button6 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=8, columnspan=3, sticky="w"+"e"+"n"+"s")
scoreText = Label(screen, text="Score: " + str(score), width=25, height=2)
scoreText.grid(row=9, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
After you change score you have to replace text in label
score += 1
scoreText['text'] = "Score: " + str(score)
Full code which replaces text in buttons instead of creating new ones.
import tkinter as tk
import random
def test():
def test1():
global score
if ticket1 == 1:
button1.config(text="RIP", bg="red")
else:
button1.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test2():
global score
if ticket1 == 2:
button2.config(text="RIP", bg="red")
else:
button2.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test3():
global score
if ticket1 == 3:
button3.config(text="RIP", bg="red")
else:
button3.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test4():
global score
if ticket2 == 1:
button4.config(text="RIP", bg="red")
else:
button4.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test5():
global score
if ticket2 == 2:
button5.config(text="RIP", bg="red")
else:
button5.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test6():
global score
if ticket2 == 3:
button6.config(text="RIP", bg="red")
else:
button6.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
ticket1 = random.randint(1, 3)
ticket2 = random.randint(1, 3)
button1 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button2 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="wens")
button3 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button4 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button5 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="wens")
button6 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
# --- main --
score = 0
screen = tk.Tk()
button_start = tk.Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button_start.grid(row=8, columnspan=3, sticky="wens")
label_score = tk.Label(screen, text="Score: 0", width=25, height=2)
label_score.grid(row=9, columnspan=3, sticky="wens")
screen.mainloop()