PySimpleGUI调用window.Read()出现expected integer but got "New"错误
问题原因
报错核心是font参数的格式不符合要求。PySimpleGUI的font参数仅支持两种合法格式:
- 字符串格式:
"字体名 字号 可选样式",例如"Times New Roman 16 bold" - 元组格式:
(字体名字符串, 字号整数, 可选样式字符串),例如("Times New Roman", 16, "bold")
你代码里的错误点:
第二个窗口(发牌页面)的sg.Text('The dealer has dealt the cards:', font=('Times New Roman')) 中,('Times New Roman') 不是元组,只是被括号包裹的普通字符串,等价于直接传入"Times New Roman"。PySimpleGUI解析时会按空格拆分这个字符串,把拆分出的第二个值New当成字号尝试转成整数,就触发了expected integer but got "New"的报错。
修复方案
将发牌页面的font参数补全字号即可,你可以根据需求调整字号大小,示例修改如下:
# 原错误写法 # [sg.Text('The dealer has dealt the cards:', font=('Times New Roman'))], # 修改后写法,字号可自行调整 [sg.Text('The dealer has dealt the cards:', font=('Times New Roman', 12))],
修改后完整可运行代码:
import PySimpleGUI as sg import random # 全局变量定义 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] hand = [] dealer_hand = [] random1 = random.randint(1,10) random2 = random.randint(1,10) dealer1 = random.randint(1,10) dealer2 = random.randint(1,10) # 欢迎页布局 welcome = [ [sg.Text('Welcome to blackjack', text_color='#000000', font=('Times New Roman', 16,'bold'))], [sg.Text('Rules: You will be dealt 2 cards and the same for the dealer. The dealer will', text_color='#000000')], [sg.Text(' only reveal one of his cards. Your objective is to reach close to 21 without crossing it', text_color='#000000')], [sg.Text(' Aces can be 1 or 11, all face cards are 10. If you choose to stand, your total should be more than the dealer', text_color='#000000')], [sg.Button('Start!')] ] window = sg.Window('Welcome', background_color = '#FFFFFF').Layout(welcome) window.read() window.close() # 发牌页布局 first = [ [sg.Text('The dealer has dealt the cards:', font=('Times New Roman', 12))], [sg.Text(f'Your two starting cards are {random1} and {random2}')], [sg.Text(f'Dealer shows his faced up card: {dealer1}')], [sg.Button('Hit'), sg.Button('Stand')] ] window = sg.Window('First set', first) event, values = window.Read() print(event) window.close()
内容的提问来源于stack exchange,提问作者josh galecki
相关产品推荐
相关产品推荐

