You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter设置600x400窗口分辨率不生效求助

解决Tkinter窗口分辨率不生效的问题

嘿,我懂你遇到的麻烦了——明明设置了600x400的窗口尺寸,结果运行时还是默认大小,只有添加组件后才会被撑开。咱们直接揪出问题核心:

你踩了一个很容易忽略的小坑:geometry是Tk窗口对象的方法,不是属性,你用赋值语句schermata.geometry = ('600x400')根本不会触发窗口尺寸设置,正确的做法是调用这个方法。

具体修正步骤:

  1. 修复窗口尺寸设置逻辑:把赋值操作改成方法调用
    错误代码:

    schermata.geometry = ('600x400')
    

    正确代码:

    schermata.geometry('600x400')
    
  2. 给按钮显式指定父组件(可选但推荐):你的按钮没有绑定所属窗口,虽然Tkinter会默认关联主窗口,但显式写上schermata参数能让代码更清晰,避免潜在的组件归属问题:
    错误代码:

    bottone = tk.Button(text = 'Gioca!', command=lambda:risposte())
    

    正确代码:

    bottone = tk.Button(schermata, text = 'Gioca!', command=lambda:risposte())
    

完整修正后的代码:

import tkinter as tk
import random

schermata = tk.Tk()
# 修正:调用geometry方法设置窗口尺寸
schermata.geometry('600x400')
schermata.title('8 Ball Game!')

input_testo = tk.StringVar()
entrata = tk.Entry(schermata, textvariable = input_testo, width = 30, borderwidth = 5)
entrata.grid(row = 0, column = 10 )

parole = ['Secondo me si', 'Credo di si', 'Per niente', 'Non dire cavolate', 'Stai scherzando vero?', 'Ma che razza di domande sono', '...', 'Certo', 'Stai zitto']

def risposte():
    global parole
    input_testo.set(random.choice(parole))

# 修正:添加父组件schermata
bottone = tk.Button(schermata, text = 'Gioca!', command=lambda:risposte())
bottone.grid(row = 2, column = 5)

if __name__ == '__main__':
    schermata.mainloop()

现在运行代码,窗口就会直接以600x400的尺寸打开啦~

内容的提问来源于stack exchange,提问作者Michele Nastasi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:57:41