So... I'm tinkering with some basic python/tkinter programs, and translating the code from python 2.x in the book I'm reading, to 3.x to make sure I understand everything. I was also attempting to write the code with 'proper' named imports instead of wild card import i.e. from tkinter import * but its not working out so well...

What has me baffled at the moment is this: the original code does a wildcard import of tkinter, and seems to be able to 'get away with' not using quotes around parameter variables like sticky=W, while if I do a named import I have to use quotes around the 'W' or I get an error Unresolved reference 'W'.

Example code (wildcard import):

from tkinter import *
root = Tk()

Label(root, text="Username").grid(row=0, sticky=W)
Label(root, text="Password").grid(row=1, sticky=W)
Entry(root).grid(row=0, column=1, sticky=E)
Entry(root).grid(row=1, column=1, sticky=E)
Button(root, text="Login").grid(row=2, column=1, sticky=E)

root.mainloop()

Named import:

import tkinter as tk

root = tk.Tk()

tk.Label(root, text="Username").grid(row=0, sticky='W')
tk.Label(root, text="Password").grid(row=1, sticky='W')
tk.Entry(root).grid(row=0, column=1, sticky='E')
tk.Entry(root).grid(row=1, column=1, sticky='E')
tk.Button(root, text="Login").grid(row=2, column=1, sticky='E')

root.mainloop()

Both work, but why does python recognize it one way one time, and not the other?

有帮助吗?

解决方案

from tkinter import *

Loads everything from tkinter module, and puts it in the global namespace.


import tkinter as tk

Loads everything from tkinter module, and put it all in the tk namespace. So Label is now tk.Label, and W is tk.W


Your third option, which is better when you only need a few objects from the module, would be:

from tkinter import Label, Entry, Button, W, E, Tk

Etc. Again, better when you just need one or two. Not good for your situation. Just included for completeness.


Fortunately you only have one import * or you'd have a much harder time determining which module everything came from!


Edit:

tkinter.W = 'w'
tkinter.E = 'e'
tkinter.S = 's'
tkinter.N = 'n'

They're just constants. You could pass the string value and it would work just as well.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top