为何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:
- Wrong variable type for
textvariable: Tkinter'sEntrycomponent requirestextvariableto be bound to a Tkinter-specific variable object (likeStringVar,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. - Global variable typo: You wrote
global coordinstead ofglobal coord2—this isn't the direct cause of the sync, but it would break any future attempts to reference thecoord2variable 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
相关产品推荐
相关产品推荐

