Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

tkinter Entry <Return> event doesn't execute function

I’m just starting learning python and I tried to make Rock, Paper, Scissors game. However when I press Enter after filling my username – it can’t execute the function that’s the same func the ‘Play’ button executes.

def start_game():
    controller.set_user_name(input_name.get())
    frame.destroy()
    logo_label.destroy()
    name.destroy()
    input_name.destroy()
    sub.destroy()
    main_game_window()
input_name=Entry(root,font='arial 10 bold')
input_name.bind('<Return>',start_game)  
input_name.place(x=275,y=290)

sub=Button(root,text="Let's Play",font='lucida 10 bold',bg='black',fg='white',command=start_game)
sub.place(x=305,y=350)

Also the ‘computer’ picks only once, although it’s set to pick random on every round. Will be thankfull if someone gives me an advice.

import random
choices = ('Rock', 'Paper', 'Scissors')

class Player:
    def __init__(self,name='Computer',score=0, choice=random.choice(choices)):
        self.name = name
        self.score = score
        self.choice = choice
        
    def get_name(self):
        return self.name
    
    def set_name(self, name):
        self.name = name
    
    def get_score(self):
        return self.score
    
    def increase_score(self):
        self.score += 1
        
    def set_choice(self, choice=random.choice(choices)):
        self.choice = choice
        
    def get_choice(self):
        return self.choice

https://github.com/ITWebFun/rock-paper-scissors.git

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For the entry, although I’m not passing an argument it gives me an error

File "C:\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
TypeError: start_game() takes 0 positional arguments but 1 was given

>Solution :

You have to add ‘event’ as a parameter in your start_game() function. Modified code:

def start_game(event):
    controller.set_user_name(input_name.get())
    frame.destroy()
    logo_label.destroy()
    name.destroy()
    input_name.destroy()
    sub.destroy()
    main_game_window()

Then the start_game() function will be able to accept the Button command.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading