2016-11-04 7 views
-1

に定義されていません。ボタンは、pythonの3

import tkinter 

top = tkinter.Tk() 

def callback(): 
    print ("click!") 

button = Button(top, text="OK", command=callback) 
top.mainloop() 

私はエラーを取得する:Tkinterのモジュールをインポート

NameError: name 'Button' is not defined 
+0

オンセすでに代わりに 'トップ= Tkの(の'トップ= tkinter.Tkを() 'を書きました) '。 'button = Button(top、text =" OK "、command = callback)がなぜ機能しないのかは本当に明白です。私はあなたに推測することを提案しますが、既に十分な回答があります – Aemyl

答えて

0

はあなたがモジュールオブジェクトへのアクセスを提供します(tkinter)。その中のどのクラスにもアクセスできます。 tkinter.ButtonだけではなくButton

import tkinter 

top = tkinter.Tk() 

def callback(): 
    print ("click!") 

button = tkinter.Button(top, text="OK", command=callback) 
top.mainloop() 

それとも、特にモジュールから必要なクラスをインポートすることができます

import tkinter 
from tkinter import Button 

top = tkinter.Tk() 

def callback(): 
    print ("click!") 

button = Button(top, text="OK", command=callback) 
top.mainloop() 
+0

私はこれを試したときにエラーを取得しませんでしたが、ボタンはウィンドウに表示されませんでした... – Binyamin

+0

http://effbot.org/tkinterbook/tkinter-hello-tkinter.htm。最初の例を自分のものと比較して、あなたのプログラムに欠けているものを見てください。 – freidrichen

0

としては、あなたが試してみてください「ボタンが」

が定義されていない、と述べました:

import tkinter 

top = tkinter.Tk() 

def callback(): 
    print ("click!") 

button = tkinter.Button(top, text="OK", command=callback) 
top.mainloop() 
0

@freidrichen respあなたはその後、

from tkinter import * 

または

import tkinter as tk 

(推奨されません)を使用することができますいずれか

tk.Button(top, text="OK", command=callback) 
+0

推奨されていないと述べています。 – scotty3785

+0

FWIWの 'import tkinter as tk'は' tkinter import * 'よりも優れています。これは、約130個のTkinter名をグローバル名前空間にダンプするためです。名前が衝突する可能性があります。特に、「スター」インポートを使用して別のモジュールの内容をインポートすると、(すでに遅いグローバル名のルックアッププロセスが遅くなる可能性があります) –

+0

合意。初心者にとっては、tkinterのチュートリアルやサンプルのほとんどが 'from tkinter import *'を使っているので、これを理解することは難しいです。 – scotty3785