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

为何Tkinter两个Entry组件输入内容同步显示?技术求助

问题分析与解决方案

Got it, let's figure out why your two Entry widgets are syncing up unexpectedly—this is a common pitfall when working with Tkinter's variable bindings!

核心问题原因

Your code has two key issues causing the sync behavior:

  1. Wrong variable type for textvariable: Tkinter's Entry component requires textvariable to be bound to a Tkinter-specific variable object (like StringVar, IntVar), not a regular Python string. When you pass a plain string, Tkinter does some implicit under-the-hood handling that ends up making both Entries share the same default variable, hence the sync.
  2. Global variable typo: You wrote global coord instead of global coord2—this isn't the direct cause of the sync, but it would break any future attempts to reference the coord2 variable correctly.

Fixed Code

Here's the corrected version that resolves both issues:

import tkinter
import tkinter.font as tkFont
from tkinter import *

def tkinter_window():
    global coord1Entry
    global coord2Entry
    
    tk = Tk()
    tk.title("Math Graph")
    
    # Create Tkinter StringVar objects (this is the critical fix!)
    coord1 = StringVar(value="0,0")
    coord2 = StringVar(value="0,0")
    
    font1 = tkFont.Font(family="Source Code Pro", size=16)
    font2 = tkFont.Font(family="Source Code Pro", size=10)
    
    coord1Label = Label(tk, text='X coordinate 1:\n( "x,y", no parentheses )', font=font1)
    coord2Label = Label(tk, text='Y coordinate 2:\n( "x,y", no parentheses )', font=font1)
    
    # Bind each Entry to its own StringVar
    coord1Entry = Entry(tk, textvariable=coord1)
    coord2Entry = Entry(tk, textvariable=coord2)
    
    # Layout setup
    coord1Label.grid(row=0, column=0, padx=15, pady=15)
    coord2Label.grid(row=1, column=0, padx=15, pady=15)
    coord1Entry.grid(row=0, column=1, padx=5, pady=5)
    coord2Entry.grid(row=1, column=1, padx=5, pady=5)
    
    tk.mainloop()

tkinter_window()

Quick Extra Tip

If you need to retrieve the values from the Entries later, just use coord1.get() and coord2.get() to fetch the current string content of each input box. For cleaner code long-term, consider wrapping your UI in a class instead of relying on global variables—it'll make your code easier to maintain and expand.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:47:34