PySimpleGUI:无法完成关键字为0的元素上的操作。

huangapple go评论73阅读模式
英文:

PySimpleGUi: Unable to complete operation on element with key 0

问题

I'm creating a program that asks the user to guess a certain number that the computer will draw. In the tutorial I'm following to make this program, the tutor uses PySimpleGUI to create an interactive window. This is the program code:

import random
import PySimpleGUI as sg

class GuessNumberSimulator():
    def __init__(self):
        self.random_value = 0
        self.min_value = 1
        self.max_value = 60
        self.number_chances = 10

    def Start(self):
        layout = [
            [sg.Text('Your guess', size=(20,0))],
            [sg.Input(size=(18,0), key='GuessValue')],
            [sg.Button('Guess!')],
            [sg.Output(size=(20,10))]
        ]
        # create a window
        self.window = sg.Window('Guess Number Simulator', layout=layout)

        self.GenerateNumber()
        self.RequestNumber()
        try:
            while True:
                # receive the values
                self.event, self.values = self.window.read()
                self.guess_value = self.values['GuessValue']
                if self.event == 'Guess!':
                    while self.number_chances != 0:
                        if int(self.guess_value) > self.random_value:
                            print(f'\033[1;32mA little less! (Number of chances: {self.number_chances})\033[m')
                            self.number_chances -= 1
                            self.RequestNumber()
                        elif int(self.guess_value) < self.random_value:
                            print(f'\033[1;31mA little more! (Number of chances: {self.number_chances})\033[m')
                            self.number_chances -= 1
                            self.RequestNumber()
                        if int(self.guess_value) == self.random_value:
                            self.try_again = False
                            print(f'\033[1;34m🎉🎉🎉 CONGRATULATIONS! The number chosen is {self.random_value}! You´re right! 🎉🎉🎉\033[m')
                            break
                        if self.number_chances == 0:
                            print(f'\033[1;35m😢😢😢 What a shame! Your chances are over! The number chosen was {self.random_value}! Better luck next time!\033[m')
        except:
            print('\033[1;031mPlease insert only integer numbers!\033[m')

    def RequestNumber(self):
        self.guess_value = input('Guess any number: ')

    def GenerateNumber(self):
        self.random_value = random.randint(self.min_value, self.max_value)

Guess1 = GuessNumberSimulator()
Guess1.Start()

When I try to run the program, a PySimpleGUI window pops up with this message:

Unable to complete operation on element with key 0. You cannot perform (such as calling update) on an Element until window.read() is called or finalize=True when Window created. Adding a "finalize=True" parameter to your Window creation will likely fix this.

This is a print of the error message:

I tried to check which key the problem was talking about. I tried changing the value of key='GuessValue' to 1, thinking this was the key cited by the error message, but the same message came up. I expected to see the PySimpleGUI interactive window working, but to no avail. The program is running fine in the terminal, but the interactive window doesn't even appear when I try to use the PySimpleGUI in the source code. I tried putting finalize=True" in both self.window = sg.Window('Guess Number Simulator', layout=layout, finalize=True) and self.event, self.values = self.window.read(finalize=True), but the PySimpleGUI window doesn't show anything anymore, it goes blank and doesn't work.

英文:

I'm creating a program that asks the user to guess a certain number that the computer will draw. In the tutorial I'm following to make this program, the tutor uses PySimplesGUI to create an interactive window. This is the program code:

import random
import PySimpleGUI as sg
class GessNumberSimulator():
def __init__(self):
self.randon_value = 0
self.min_value = 1
self.max_value = 60
self.number_chances = 10
def Start(self):
layout = [
[sg.Text(&#39;Your guess&#39;,size=(20,0))],
[sg.Input(size=(18,0),key=&#39;GuessValue&#39;)],
[sg.Button(&#39;Guess!&#39;)],
[sg.Output(size=(20,10))]
]
# create a window
self.window = sg.Window(&#39;Guess Number Simulator&#39;, layout=layout)
self.GenerateNumber()
self.RequestNumber()
try:
while True:
# receive the values
self.event, self.values = self.window.Read()
self.guess_value = self.values[&#39;GuessValue&#39;]
if self.event == &#39;Guess!&#39;:
while self.number_chances != 0:
if int(self.guess_value) &gt; self.randon_value:
print(f&#39;\033[1;32mA little less! (Number of chances: {self.number_chances})\033[m&#39;)
self.number_chances -= 1
self.RequestNumber()
elif int(self.guess_value) &lt; self.randon_value:
print(f&#39;\033[1;31mA little more! (Number of chances: {self.number_chances})\033[m&#39;)
self.number_chances -= 1
self.RequestNumber()
if int(self.guess_value) == self.randon_value:
self.try_again = False
print(f&#39;\033[1;34m&#127881;&#127881;&#127881; CONGRATULATIONS! The number chosen is {self.randon_value}! You &#180; re right! &#127881;&#127881;&#127881;\033[m&#39;)
break
if self.number_chances == 0:
print(f&#39;\033[1;35m&#128546;&#128546;&#128546; What a shame! Your chances is over! This number chosen was {self.randon_value}! More luck in the next time!\033[m&#39;)
except:
print(&#39;\033[1;031mPlease insert only integers numbers!\033[m&#39;)
def RequestNumber(self):
self.guess_value = input(&#39;Guess any number: &#39;)
def GenerateNumber(self):
self.randon_value = random.randint(self.min_value, self.max_value)
Guess1 = GessNumberSimulator()
Guess1.Start()

When I try to run the program, a PySimpleGUI window pops up with this message:

> Unable to complete operation on element with key 0. You cannot perform (such as calling update) on an Element until window.read() is called or finalize=True when Window created. Adding a "finalize=True" parameter to your Window creation will likely fix this.

This is a print of the error message:

I tried to check which key the problem was talking about. I tried changing the value of key=&#39;GuessValue&#39; to 1 thinking this was the key cited by the error message, but the same message came up. I expected to see the PySimplesGUI interactive window working, but to no avail. The program is running fine in the terminal, but the interactive window doesn't even appear when I try to use the PySimplesGUI in the source code. I tried putting finalize=True&quot; in both self.window = sg.Window(&#39;Guess Number Simulator&#39;, layout=layout, finalize=True) and self.event , self.values ​​= self.window.Read(finalize=True), but the PySimpleGUI window doesn't show anything anymore, it goes blank and doesn't work.

答案1

得分: 1

Here is the translated code:

找不到代码中的异常要使用 GUI不应同时使用控制台输入或输出

修订后的代码

```python
import random
import PySimpleGUI as sg

class GuessNumberSimulator():
    def __init__(self):
        self.random_value = 0
        self.min_value = 1
        self.max_value = 60
        self.number_chances = 10

    def Start(self):
        layout = [
            [sg.Text('你的猜测'), sg.Input(size=5, key='GuessValue'), sg.Button('猜!', bind_return_key=True)],
            [sg.Output(size=(80, 10))]
        ]
        self.window = sg.Window('猜数字模拟器', layout=layout)
        self.GenerateNumber()

        while True:

            event, values = self.window.read()

            if event == sg.WIN_CLOSED:
                break

            elif event == "猜!":
                self.window['GuessValue'].update(select=True)
                entry = values['GuessValue']
                if not entry.isdigit():
                    print(f"错误的数字,范围在 {self.min_value}{self.max_value} 之间!")
                    continue
                try:
                    guess_value = int(entry)
                except ValueError:
                    print(f"错误的数字,范围在 {self.min_value}{self.max_value} 之间!")
                    continue
                if self.number_chances != 0:
                    if guess_value > self.random_value:
                        print(f'再小一点!(剩余机会次数:{self.number_chances})')
                        self.number_chances -= 1
                    elif guess_value < self.random_value:
                        print(f'再大一点!(剩余机会次数:{self.number_chances})')
                        self.number_chances -= 1
                    elif guess_value == self.random_value:
                        sg.popup(f'🎉🎉🎉 恭喜你!选择的数字是 {self.random_value}!你猜对了! 🎉🎉🎉')
                        break
                    if self.number_chances == 0:
                        sg.popup(f'😢😢😢 太可惜了!你的机会用完了!选择的数字是 {self.random_value}!下次好运!😢😢😢')
                        break
        self.window.close()

    def GenerateNumber(self):
        self.random_value = random.randint(self.min_value, self.max_value)


Guess1 = GuessNumberSimulator()
Guess1.Start()

I've translated the code for you.

英文:

Didn't find the exception for your code. To work with a GUI, you should not use console input or output at the same time.

Revised code

import random
import PySimpleGUI as sg

class GessNumberSimulator():
    def __init__(self):
        self.randon_value = 0
        self.min_value = 1
        self.max_value = 60
        self.number_chances = 10

    def Start(self):
        layout = [
            [sg.Text(&#39;Your guess&#39;), sg.Input(size=5, key=&#39;GuessValue&#39;), sg.Button(&#39;Guess!&#39;, bind_return_key=True)],
            [sg.Output(size=(80, 10))]
        ]
        self.window = sg.Window(&#39;Guess Number Simulator&#39;, layout=layout)
        self.GenerateNumber()

        while True:

            event, values = self.window.read()

            if event == sg.WIN_CLOSED:
                break

            elif event == &quot;Guess!&quot;:
                self.window[&#39;GuessValue&#39;].update(select=True)
                entry = values[&#39;GuessValue&#39;]
                if not entry.isdigit():
                    print(f&quot;Worng Number, range from {self.min_value} to {self.max_value} !&quot;)
                    continue
                try:
                    guess_value = int(entry)
                except ValueError:
                    print(f&quot;Worng Number, range from {self.min_value} to {self.max_value} !&quot;)
                    continue
                if self.number_chances != 0:
                    if guess_value &gt; self.randon_value:
                        print(f&#39;A little less! (Number of chances: {self.number_chances})&#39;)
                        self.number_chances -= 1
                    elif guess_value &lt; self.randon_value:
                        print(f&#39;A little more! (Number of chances: {self.number_chances})&#39;)
                        self.number_chances -= 1
                    elif guess_value == self.randon_value:
                        sg.popup(f&#39;&#127881;&#127881;&#127881; CONGRATULATIONS! The number chosen is {self.randon_value}! You &#180; re right! &#127881;&#127881;&#127881;&#39;)
                        break
                    if self.number_chances == 0:
                        sg.popup(f&#39;&#128546;&#128546;&#128546; What a shame! Your chances is over! This number chosen was {self.randon_value}! More luck in the next time!&#39;)
                        break
        self.window.close()

    def GenerateNumber(self):
        self.randon_value = random.randint(self.min_value, self.max_value)


Guess1 = GessNumberSimulator()
Guess1.Start()

huangapple
  • 本文由 发表于 2023年5月17日 20:32:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定