I was testing an app I was writing but I just get a blank window and no widgets.
from Tkinter import*
class App(Frame):
def _init_(self, master):
frame = Frame(master)
frane.pack()
self.instruction = Label(frame, text = 'Password:')
self.instruction.pack()
self.button = Button(frame, text = 'Enter', command = self.reveal)
self.button.pack()
root = Tk()
root.title('Password')
root.geometry('350x250')
App(root)
root.mainloop()
You have a couple of typos. The first is in the name of the constructor method:
def _init_(self, master):
Should read:
def __init__(self, master):
Note the double underscore - see the docs for Python objects.
The second is inside your constructor:
frane.pack()
You're also missing a declaration for a method named 'reveal' in your App class:
self.button = Button(frame, text="Enter", command=self.reveal)
The working example reads:
from Tkinter import *
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.pack()
frame = Frame()
frame.pack()
self.instruction = Label(frame, text="Password:")
self.instruction.pack()
self.button = Button(frame, text="Enter", command=self.reveal)
self.button.pack()
def reveal(self):
# Do something.
pass
root = Tk()
root.title("Password")
root.geometry("350x250")
App(root)
root.mainloop()
See also: The Tkinter documentation.
Related
I am trying to develop a GUI using Tkinter and Python2.7 by following a few tutorials and their documentation. Right now i am stuck on how to keep my frame a constant size (Because i want to have a nice background).
I have tried to use geometry() function from their documentation but always returns with an error - geometry attribute not found
import Tkinter as tk
import ttk
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
# Initialize Tkinter
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "ScraperBot")
tk.Tk.geometry('250x250')
# Make a container
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# Define Frames
self.frames = {}
for myFrame in (HomePage, PageOne, PageTwo):
frame = myFrame(container, self)
self.frames[myFrame] = frame
frame.grid(row=0, column=0, sticky="nsew")
# Which frame do we wanna display?
self.show_frame(HomePage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class HomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# Make a Label
label = ttk.Label(self, text="HomePage", font=LARGE_FONT)
label.pack(pady=10, padx=10) # Padding on top and bottom
# Add a Button to navigate from one page to another
button1 = tk.Button(self, text="Go to Page_1", fg="red",
command= lambda: controller.show_frame(PageOne))
button1.pack()
# Add a Button to navigate from one page to another
button6 = tk.Button(self, text="Go to Page_2", fg="green",
command= lambda: controller.show_frame(PageTwo))
button6.pack()
def button_Function(parameter):
print(parameter)
app = Application()
app.mainloop()
I am trying to create a GUI for the analyzeMFT python program. So far this is what i have
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
from ttk import *
import analyzeMFT
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.filename = ""
self.initUI()
def initUI(self):
self.parent.title("Mtf Analyzer")
#initializing and configuring menubar
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Open file", command=self.fileOpen)
fileMenu.add_command(label="Exit", command=self.onExit)
menubar.add_cascade(label="File", menu=fileMenu)
#specify grid row and column spaces
self.pack(fill=BOTH, expand=True)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
lbl = Label(self, text="File Name")
lbl.grid(row=1, column=0, sticky=W, pady=4, padx=5)
filename_area = Entry(self)
filename_area.grid(row=1, column=1, columnspan=3,
padx=5)
analize_button = Button(self, text="Analize", command=self.processFile)
analize_button.grid(row=1, column=4, padx=5)
area = Text(self)
area.grid(row=2, column=1, columnspan=2, rowspan=4,
padx=5, sticky=E+W+S+N)
#configure the raw output view
def onExit(self):
self.quit()
#this function selects and opens the file to analize
def fileOpen(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
#populate the filename field
#do the processing of the file obtained. Populate the file NAME entry or
#send the filename to the analyzeMFT.py
def processFile(self):
filei = "-f "+self.filename
arguments = [filei, '-o '+self.filename+' .csv']
analyzeMFT.main(arguments)
#get and set methods for the entry field
def get(self):
return self.filename_area.get()
def set(self, value):
filename_area.set(value)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
This code creates a gui that i can chose a file to analyze using the analyzeMFT program. There are two problems.
1.analyzeMFT is meant to be run on command line. I am not able to pass the file name I get from the GUI to the analyzeMFT.py Here are the contents of analyzeMFT.py
#!/usr/bin/python
try:
from analyzemft import mftsession
except:
from .analyzemft import mftsession
def main():
session = mftsession.MftSession()
session.mft_options()
session.open_files()
session.process_mft_file()
if __name__ == "__main__":
main()
Next, when i run the analyzerMFT in cmd and enable debug mode, it prints every detail on the screen. How can I direct that out to a window i have shown below
I want it somehow to look like this
Sorry if the explanation is very long. I've been working on it for days.
Instead of using print like you would normally use to display results to the console you can use insert() on your text box.
EDIT:
First change:
area = Text(self)
area.grid(row=2, column=1, columnspan=2, rowspan=4,
padx=5, sticky=E+W+S+N)
To:
self.area = Text(self)
self.area.grid(row=2, column=1, columnspan=2, rowspan=4,
padx=5, sticky=E+W+S+N)
This way your text box is set up as a class attribute that we can use.
Then use:
self.area.delete(1.0, "end") # to clear text box
self.area.insert("end", your_output variable or string) # to insert content
I am using Tkinter and would like to have the option to clear my graph and draw a new one in its place. I'm not sure what to put in my callback to do this. The best I can do so far is to replace the graph with a white box. The new graph is drawn underneath (which isn't ideal) and also appears as a blank white box for some reason. Apologies for asking such a basic question but I'm new to python and couldn't find an example using subplots on here.
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import Tkinter as tk
from Tkinter import *
import ttk
class Helmholtz_App(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Helmholtz Coils Data")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (PageOne,PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(PageOne)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
fig1 = Figure(figsize=(5,5), dpi=100)
a = fig1.add_subplot(111)
def callback():
volt=[[0,1,2,3,4],[0,1,2,3,4]]
a.plot(volt[1],volt[0],'bo')
canvas = FigureCanvasTkAgg(fig1, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def ClearCallback():
#problem line
#~~~~~~~~~~~
fig1.clf()
# ~~~~~~~~~~
clearbutton.destroy()
clearbutton=ttk.Button(self, text="Clear", command=ClearCallback)
clearbutton.pack()
b=ttk.Button(self, text="Plot Data", command=callback)
b.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
app = Helmholtz_App()
app.mainloop()
The code is based on this tutorial 1
I want the code to work so the "take data" button creates a graph, and the "clear" button removes that graph. Then when the "take data" button is pressed again it will put a new graph in the same place with none of the data from the old graph present.
Here is the
I'm following a Sentdex tutorial, found here, specifically this part about creating a GUI in Python. However the tutorial is in python 3 and I'm using 2.7.
Importing Tkinter is fine, however when I come to importing ttk and then inheriting it into the class, a problem arises. In python 2.7 ttk is a separate module, which means is not in the Tkinter module.
import Tkinter as tk
import ttk
LARGE_FONT= ("Verdana", 12)
class SeaOfBTCApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Seal of BTC")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
The problem appears to be when the classes inherit Tk, when I do:
button = ttk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
It doesn't use ttk, the buttons still look the same (like when it was tk.Button). How can I make the buttons look like the ttk buttons.
Full code:
import Tkinter as tk
from ttk import *
LARGE_FONT= ("Verdana", 12)
class SeaOfBTC(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Sea of BTC")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = ttk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = ttk.Button(self, text="Visit Page 2",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = ttk.Button(self, text="Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = ttk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.pack()
app = SeaOfBTC()
app.mainloop()
If you use ttk.Button, it absolutely will use the ttk button. It can't possibly do anything else because you're explicitly saying to use the Button class from the ttk module.
Note: Depending on what platform you're on, the tk and ttk buttons may look identical.
Other than the way you do the imports, there's virtually no difference between tkinter in python 2.x and 3.x.
I am trying to make an android application...I am trying to switch from menu to server or client according to user input...but i am not able to switch from one class to another...main thing which pissed me off is that print statement inside ServerScreen is working but other part is not working...don't know why
Code:---
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class MenuScreen(Screen):
def __init__(self, **kwargs):
super(MenuScreen, self).__init__(**kwargs)
def Server(instance):
self.clear_widgets()
self.add_widget(Label ( text = 'Inside server function'))
server = ServerScreen()
#return server
#server.function()
self.add_widget(Label ( text = 'What Type Of Service You Want...???'))
button1 = Button(text = 'Server',size_hint = (None,None),pos = (0,0))
self.add_widget(button1)
button1.bind(on_press = Server)
button2 = Button(text = 'Client',size_hint = (None,None),pos = (100,0))
self.add_widget(button2)
#button2.bind(on_press = Client)
class ServerScreen(Screen):
def __init__(self, **kwargs):
super(ServerScreen, self).__init__(**kwargs)
print('Inside server screen')
self.clear_widgets()
self.add_widget(Label (text = 'Working As A Server'))
print("Hellooooooooooo")
sm = ScreenManager()
sm.add_widget(MenuScreen(name='Menu'))
sm.add_widget(ServerScreen(name='Server'))
#sm.add_widget(ClientScreen(name='Client'))
class FileApp(App):
def build(self):
#return Menu()
return sm
if __name__ == '__main__':
FileApp().run()
In which part i am making mistake...please point out that part & provide how can i solve that...
Output--->
Inside server screen
Hellooooooooooo
Look at my solution inspired by this excellent comment from inclement : Kivy: Changing screens in screen manager with an on_press event
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class MenuScreen(Screen):
def switching_function(*args):
global sm
sm.current = 'Server'
def __init__(self, **kwargs):
super(MenuScreen, self).__init__(**kwargs)
# def Server(instance):
# self.clear_widgets()
# self.add_widget(Label ( text = 'Inside server function'))
# server = ServerScreen()
# #return server
# #server.function()
self.add_widget(Label ( text = 'What Type Of Service You Want...???'))
button1 = Button(text = 'Server',size_hint = (None,None),pos = (0,0))
self.add_widget(button1)
# button1.bind(on_press = Server)
button1.bind(on_press = self.switching_function)
button2 = Button(text = 'Client',size_hint = (None,None),pos = (100,0))
self.add_widget(button2)
#button2.bind(on_press = Client)
class ServerScreen(Screen):
def __init__(self, **kwargs):
super(ServerScreen, self).__init__(**kwargs)
print('Inside server screen')
self.clear_widgets()
self.add_widget(Label (text = 'Working As A Server'))
print("Hellooooooooooo")
sm = ScreenManager()
sm.add_widget(MenuScreen(name='Menu'))
sm.add_widget(ServerScreen(name='Server'))
#sm.add_widget(ClientScreen(name='Client'))
class FileApp(App):
def build(self):
#return Menu()
return sm
The problem is with server = ServerScreen() inside
def Server(instance):
self.clear_widgets()
self.add_widget(Label ( text = 'Inside server function'))
server = ServerScreen()
#return server
#server.function()
It creates a new ServerScreen, not the ServerScreen which is actually displayed at the moment (so
Inside server screen
Hellooooooooooo
is displayed, but the ScreenManager has no idea that this additional Screen is existing.