I have 2 different python GUI menus in 2 different scripts.
A dropdown list to select
A menu where numbers can be input and output at the same GUI
I want to merge these 2 together so that both appear in the same GUI menu.
I am having trouble doing it because the structure in both python scripts is different.
Please advice.
Sharing both scripts below:
1st one
from tkinter import *
class Custombox:
def __init__(self, title, text):
self.title = title
self.text = text
def store():
self.new = self.entry.get() # storing data from entry box onto variable
if self.new == '50': # checking
a.change('ACCEPTED') # changing text
elif self.new == '40':
a.change('Increase frequency') # else, changing text
else:
a.change('Decrease frequency') # else, changing text
self.win = Toplevel()
self.win.title(self.title)
# self.win.geometry('400x150')
self.win.wm_attributes('-topmost', True)
self.label = Label(self.win, text=self.text)
self.label.grid(row=0, column=0, pady=(20, 10), columnspan=3, sticky='w', padx=10)
self.l = Label(self.win)
self.entry = Entry(self.win, width=50)
self.entry.grid(row=1, column=1, columnspan=2, padx=10)
self.b1 = Button(self.win, text='Attack', width=10, command=store)
self.b1.grid(row=3, column=1, pady=10)
# self.b2 = Button(self.win, text='Cancel', width=10, command=self.win.destroy)
# self.b2.grid(row=3, column=2, pady=10)
def __str__(self):
return str(self.new)
def change(self, ran_text):
self.l.config(text=ran_text, font=(0, 12))
self.l.grid(row=2, column=1, columnspan=3, sticky='nsew', pady=5)
root = Tk()
root.withdraw()
a = Custombox('User learning platform', 'Select the frequency of the victim sensor.')
root.mainloop()
2nd one
from tkinter import *
root = Tk()
root.title("GUI platform")
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
# Create a Tkinter variable
tkvar = StringVar(root)
# Dictionary with options
choices = { 'URM37','HC-SR04','SRF05','Parallax PING'}
tkvar.set('') # set the default option
popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Please select the type of Sensor for attack").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
# on change dropdown value
def change_dropdown(*args):
if tkvar.get() == 'HC-SR04':
print( "Correct" )
else:
print("WRONG")
# link function to change dropdown
tkvar.trace('w', change_dropdown)
root.mainloop()
Related
I am trying to have two dropdown lists bellow two labels stating what they are. The problem is whenever i run it the second list is offset to the left. This takes place in the setupPage section and looks like so:
image of the issue
I have tried lots of combinations of sticky to no avail. Any help would be appreciated.
Code:
from tkinter import *
from tkinter import ttk
root = Tk()
def startPage(root):
content = ttk.Frame(root) #frame for plaing everything into
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100) #fram for plaxing images
lbl1 = ttk.Label(content, text="Is this a new or existing site?",font=("arial",12)) #setup of label for screen 1
yesvar = BooleanVar() #variables for check boxes later on
novar = BooleanVar()
yesvar.set(False)
novar.set(False)
one = ttk.Checkbutton(content, text="Yes", variable=yesvar, onvalue=True) #check buttons setup
two = ttk.Checkbutton(content, text="No", variable=novar, onvalue=True)
ok = ttk.Button(content, text="New", command = nextPage) #setup for buttons screen 1
cancel = ttk.Button(content, text="Existing")
content.grid(column=0, row=0) #intilises content
#frame.grid(column=0, row=0, columnspan=3, rowspan=2)
lbl1.grid(column=0, row=0, columnspan=3,pady=10,padx=10) #places the label asking the question with a gap either side for the window bindings
#name.grid(column=3, row=1, columnspan=2)
#one.grid(column=0, row=3)
#two.grid(column=1, row=3)
ok.grid(column=0, row=1,pady=10,padx=10) #places yes button 10 away from each edge
cancel.grid(column=1, row=1,pady=10,padx=10) #as above
def setupPage(root):
content = ttk.Frame(root) #frame for plaing everything into
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100) #fram for plaxing images
lbl1 = ttk.Label(content, text="Select meterial 1",font=("arial",12)) #setup of label for screen 1
lbl2 = ttk.Label(content, text = "Select meterial 2" ,font = ("arial",12))
content.grid(column=0, row=0)
lbl1.grid(column=0, row=0,columnspan=1, pady=10,padx=10)
lbl2.grid(column=1,row=0,columnspan=1,pady=10,padx=10)
clicked = StringVar()
clicked.set("lo2")
clicked2 = StringVar()
clicked2.set("lo2")
drop2 = OptionMenu(root, clicked2, "lo2", "mo3", "Lo2+mo3")
drop = OptionMenu(root, clicked, "lo2", "mo3", "Lo2+mo3")
drop.grid(column=0, row=1,pady=10,padx=10,sticky=NW)
drop2.grid(column=1, row=1,pady=10,padx=10,sticky=NW)
def nextPage():
global pagenum, root
for widget in root.winfo_children():
widget.destroy()
if pagenum == 1:
setupPage(root)
pagenum = 2
else :
startPage(root)
pagenum = 1
startPage(root)
pagenum = 1
root.mainloop()
The parent of the labels and the OptionMenus are different.
Changing the parents to root instead of content seems to work
from tkinter import *
from tkinter import ttk
root = Tk()
def startPage(root):
print("oi")
content = ttk.Frame(root) #frame for plaing everything into
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100) #fram for plaxing images
lbl1 = ttk.Label(content, text="Is this a new or existing site?",font=("arial",12)) #setup of label for screen 1
yesvar = BooleanVar() #variables for check boxes later on
novar = BooleanVar()
yesvar.set(False)
novar.set(False)
one = ttk.Checkbutton(content, text="Yes", variable=yesvar, onvalue=True) #check buttons setup
two = ttk.Checkbutton(content, text="No", variable=novar, onvalue=True)
ok = ttk.Button(content, text="New", command = nextPage) #setup for buttons screen 1
cancel = ttk.Button(content, text="Existing")
content.grid(column=0, row=0) #intilises content
#frame.grid(column=0, row=0, columnspan=3, rowspan=2)
lbl1.grid(column=0, row=0, columnspan=3,pady=10,padx=10) #places the label asking the question with a gap either side for the window bindings
#name.grid(column=3, row=1, columnspan=2)
#one.grid(column=0, row=3)
#two.grid(column=1, row=3)
ok.grid(column=0, row=1,pady=10,padx=10) #places yes button 10 away from each edge
cancel.grid(column=1, row=1,pady=10,padx=10) #as above
def setupPage(root):
#content = ttk.Frame(root) #frame for plaing everything into
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100) #fram for plaxing images
lbl1 = ttk.Label(root, text="Select meterial 1",font=("arial",12)) #setup of label for screen 1
lbl2 = ttk.Label(root, text = "Select meterial 2" ,font = ("arial",12))
#content.grid(column=0, row=0)
lbl1.grid(column=0, row=0,columnspan=1, pady=10,padx=10)
lbl2.grid(column=1,row=0,columnspan=1,pady=10,padx=10)
clicked = StringVar()
clicked.set("lo2")
clicked2 = StringVar()
clicked2.set("lo2")
drop2 = OptionMenu(root, clicked2, "lo2", "mo3", "Lo2+mo3")
drop = OptionMenu(root, clicked, "lo2", "mo3", "Lo2+mo3")
drop.grid(column=0, row=1,pady=10,padx=10,sticky=NW)
drop2.grid(column=1, row=1,pady=10,padx=10,sticky=NW)
def nextPage():
print("oi2")
global pagenum, root
for widget in root.winfo_children():
widget.destroy()
if pagenum == 1:
print("oi3")
setupPage(root)
pagenum = 2
else :
startPage(root)
pagenum = 1
startPage(root)
pagenum = 1
root.mainloop()
I have the following code to generate a two entry input dialog box and a button to close the "app".
However I cannot cannot get the values out of the outputs. They always come out as x and N. The code was not developed by me since I am a beginner with python. Can anyone give me hand with this?
from tkinter import Tk, Text, TOP, BOTH, X, N, LEFT, RIGH
from tkinter.ttk import Frame, Label, Entry, Button
class SimpleDialog(Frame):
def __init__(self):
super().__init__()
self.output1 = ""
self.output2 = ""
self.initUI()
def initUI(self):
self.master.title("Simple Dialog")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack()
lbl1 = Label(frame1, text="Input1", width=6)
lbl1.pack(side=LEFT, padx=5, pady=10)
self.entry1 = Entry(frame1)
self.entry1.pack(padx=5, expand=True)
frame2 = Frame(self)
frame2.pack()
lbl2 = Label(frame2, text="Input2", width=6)
lbl2.pack(side=LEFT, padx=5, pady=10)
self.entry2 = Entry(frame2)
self.entry2.pack(padx=5, expand=True)
frame3 = Frame(self)
frame3.pack()
btn = Button(frame3, text="Submit", command=self.onSubmit)
btn.pack(padx=5, pady=10)
def onSubmit(self):
self.output1 = self.entry1.get()
self.output2 = self.entry2.get()
self.quit()
def main():
# This part triggers the dialog
root = Tk()
root.geometry("250x150+300+300")
app = SimpleDialog()
root.mainloop()
user_input = (app.output1, app.output2)
try:
root.destroy()
except:
pass
return user_input
if __name__ == '__main__':
main()
kind regards!
I want to know how to get input from Tkinter and put it into a variable like a phone number or a piece of text.
from tkinter import *
def show_data():
print( 'My First and Last Name are %s %s' % (fname.get(), lname.get()) )
win = Tk()
Label( win, text='First Name' ).grid( row=0 )
Label( win, text='Last Name' ).grid( row=1 )
fname = Entry( win )
lname = Entry( win )
fname.grid( row=0, column=1 )
lname.grid( row=1, column=1 )
Button( win, text='Exit', command=win.quit ).grid( row=3, column=0, sticky=W, pady=4 )
Button( win, text='Show', command=show_data ).grid( row=3, column=1, sticky=W, pady=4 )
mainloop()
Maybe this can help you:
from tkinter import *
def get_variable_value():
valueresult.set( strlname.get() + ' ' + strfname.get() ) #assign val variable to other
print(valueresult.get()) #if you want see the result in the console
root = Tk()
strfname = StringVar()
strlname = StringVar()
valueresult = StringVar()
labelf = Label(root, text = 'First Name').pack()
fname = Entry(root, justify='left', textvariable = strfname).pack() #strlname get input
labell = Label(root, text = 'Last Name').pack()
lname = Entry(root, justify='left', textvariable = strlname).pack() #strfname get input
button = Button(root, text='Show', command=get_variable_value).pack()
res = Entry(root, justify='left', textvariable = valueresult).pack() #only to show result
root.mainloop()
You haven't provided any code but you could try:
class GetPhoneNbr(object):
def __init__(self):
self.root = Tk.Tk()
self.label = Tk.Label(self.root, text="Enter phone number")
self.label.pack()
self.phoneNbr = Tk.StringVar() # <- here's what you need
Tk.Entry(self.root, textvariable=self.phoneNbr).pack()
NOTE: This is a stub of code, not the entire class definition.
Below is a minimal GUI that puts what's written in an entry to a variable, which is the button's text:
import tkinter as tk
def replace_btn_text():
b['text'] = e.get()
root = tk.Tk()
e = tk.Entry(root)
b = tk.Button(root, text="Replace me!", command=replace_btn_text)
e.pack()
b.pack()
root.mainloop()
Same example but with an OOP structure:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self._create_widgets()
self._display_widgets()
def replace_btn_text(self):
""" Replaces button's text with what's written in the entry.
"""
# self._e.get() returns what's written in the
self._b['text'] = self._e.get() # entry as a string, can be assigned to a var.
def _create_widgets(self):
self._e = tk.Entry(self)
self._b = tk.Button(self, text="Replace me!", command=self.replace_btn_text)
def _display_widgets(self):
self._e.pack()
self._b.pack()
if __name__ == '__main__':
root = App()
root.mainloop()
I have reviewed the documentation on rowconfugre and columnconfigure, and I just do not quite understand how to get it working properly. With the following code, how can I get the 'src_entry' Entry box directly against the 'src' Checkbutton, regardless of what other widget is in column 1? Essentially, I need the size of the column to form to the width of whatever widget is in that space on the grid.
Thanks,
from tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.parent.title("TCPDUMP Creator")
self.centerWindow()
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=fileMenu)
self.columnconfigure(2, weight=5)
int_lbl = Label(self, text="Interface")
int_lbl.grid(row=1, column=0, sticky=W+E)
self.int_entry = Entry(self, width=15)
self.int_entry.grid(row=1, column=1)
self.anyInt = BooleanVar()
Checkbutton(self, text="Any", variable = self.anyInt).grid(row=1, column=2)
int_lbl = Label(self, text="")
int_lbl.grid(row=2, column=0, columnspan=99, sticky=W+E)
self.notSrc = BooleanVar()
Checkbutton(self, text = "Not--", variable = self.notSrc).grid(row=3, column=0, sticky=W+E)
self.srcIP = BooleanVar()
Checkbutton(self, text="Src", variable = self.srcIP).grid(row=3, column=1)
src_entry = Entry(self, width=15)
src_entry.grid(row=3, column=2)
self.AndOr = StringVar()
self.AndOr.set(None)
Radiobutton(self, text = "And", variable = self.AndOr, value = "And").grid(row=3, column=3, pady=5, padx=2, sticky=E)
Radiobutton(self, text = "Or", variable = self.AndOr, value = "Or").grid(row=3, column=4, pady=5, padx=10, sticky=W)
self.notDst = BooleanVar()
Checkbutton(self, text = "Not--", variable = self.notDst).grid(row=3, column=5, sticky=W+E)
self.dstIP = BooleanVar()
Checkbutton(self, text="Dst", variable = self.dstIP).grid(row=3,column=6, sticky=E, padx=0)
dst_entry = Entry(self, width=15)
dst_entry.grid(row=3, column=7)
int_lbl = Label(self, text="")
int_lbl.grid(row=4, column=0, columnspan=99, sticky=W+E)
self.srcordst = StringVar()
self.srcordst.set(None)
Radiobutton(self, text = "And", variable = self.srcordst, value = "And").grid(row=4, column=1, pady=5, padx=2, sticky=E)
Radiobutton(self, text = "Or", variable = self.srcordst, value = "Or").grid(row=4, column=2, pady=5, padx=10, sticky=W)
def centerWindow(self):
w = 600
h = 300
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2.7
self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))
def main():
root = Tk()
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
The best way to do layouts is to break your UI into sections, and then layout each section independently.The reason you're having difficulty is that you're trying to force everything into a single grid, but you don't have items that naturally fit into a grid. You can make it work by using lots of invisible columns and clever use of columnspan, but there are easier ways.
In this specific case, pack and a few intermediate frames is a better solution in my opinion.
From what I see, your UI is made up of four areas:
A row that has an entry for int_entry and a checkbutton
A row that has several checkboxes and radiobuttons, along with an entry
A row with an 'And' and 'Or' radiobutton
A big blank area
The way I would do it is create four frames, one for each area:
frame1 = Frame(self, ...)
frame2 = Frame(self, ...)
frame3 = Frame(self, ...)
frame4 = Frame(self, ...)
You can then use pack to stack those frames horizontally. All of them fill their area in the horizontal direction, and the last frame takes up all of the rest of the data.
frame1.pack(side="top", fill="x")
frame2.pack(side="top", fill="x")
frame3.pack(side="top", fill="x")
frame4.pack(side="top", fill="both", expand=True)
Now, you can add widgets to each frame with little concern for how they affect the rest of the display.
For example, the "Interface" label, the entry and the "Any" checkbutton can go in frame1. pack makes for a sensible choice since you want these aligned to the left of the area (I assume...).
int_lbl = Label(frame1, text="Interface")
self.int_entry = Entry(frame1, width=15)
any_cb = Checkbutton(frame1, text="Any", ...)
int_lbl.pack(side="left")
self.int_entry.pack(side="left")
any_cb.pack(side="left")
Do the same for the other frames. Within each frame you can choose to use pack or grid, as long as you consistently use pack or grid for every widget within the frame. pack is a very natural choice when you want all of your widgets aligned in one direction in the parent widget.
I wish to print from a list where the user enters an input and then has that input printed from a list. This however doesn't work without a blank string in the list as it says that the list is too short for the data to be shown in a label. I want for this to have the input printed immediately after pressing the continue button not after pressing the next button.
from tkinter import *
class Traveller:
def __init__(self, parent):
self.names = [""]
self.E_phone = "f"
self.E_name = "q"
self.count = 0
self.go = Frame(parent, width=500, height=450, bg="snow", pady=30, padx=10)
self.go.grid(row=1, column=0)
self.go.grid_propagate(0) # to reserve space required for frame
self.dataView = Frame(parent, width=500, height=500, bg="snow", pady=30, padx=10)
name = Label(self.go, text="Name:", bg="snow")
name.grid(row=1, column=0, sticky=E)
self.E_name = Entry(self.go, width=40)
self.E_name.grid(row=1, column=1, sticky=W, pady=4)
menuButton = Button(self.go, text="Continue", command=self.dataSave)
menuButton.grid(row=2, column=1, pady=4)
dataTitle = Label(self.dataView, text="Here is all of the inputted data:", bg="snow")
dataTitle.grid(row=2, column=0)
dataExit = Button(self.dataView, text="Return", command=self.returnT)
dataExit.grid(row=1, column=0, pady=5)
nextData = Button(self.dataView, text="Next", command=self.NData)
nextData.grid(row=4, column=0, pady=5)
prevData = Button(self.dataView, text="Previous", command=self.PData)
prevData.grid(row=4, column=1, pady=5)
self.everything = Label(self.dataView, text="The person" + self.names[self.count], bg = "snow")
self.everything.grid(row=3, column = 0)
def dataSave(self):
self.names.append(self.E_name.get())
self.go.grid_remove()
self.dataView.grid(row=1, column=0)
self.dataView.grid_propagate(0)
# clearing the entry boxes
self.E_name.delete(0, END)
def returnT(self):
self.dataView.grid_remove()
self.go.grid(row=1, column=0)
self.go.grid_propagate(0)
def NData(self):
self.count = self.count + 1
self.everything.configure(text = "The person " + self.names[self.count])
def PData(self):
if self.count >= 1:
self.count = self.count - 1
self.everything.configure(text = "The person " + self.names[self.count])
# main routine
if __name__ == "__main__":
root = Tk()
root.title("Traveller Details")
play = Traveller(root)
root.geometry("500x450+0+0")
root.mainloop()