tkinter text widget not able to appear on desired window - python

So i have written a simple tkinter gui that will show some command output results when prompted, only issue i'm having is the command wont appear on any other screen.
def updateipt():
text = Text(main_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line,)
text = Text(main_window, height=150, width=124)
i assumed that replacing the main_window argument above with another window would direct the text widget to a different window, but everytime i try this i get an error Which states that the window needs to be Tk(): AttributeError: 'function' object has no attribute 'tk'
How do i work around this?
Full code posted below:
#!/bin/bash
import os
import subprocess as sub
from tkinter import *
from subprocess import Popen, PIPE
def main_window():
global main_window
main_window = Tk()
main_window.title("Firewall test")
main_window.geometry("1000x700")
main_window.configure(bg="dark grey")
label1 = Label(main_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
btnproc = Button(main_window, text="Process configuration", font=('arial', 9, 'bold'), bg="light grey", fg="black",
width="30", height="2", command=lambda: process_window())
btnproc.pack(pady=20)
btnfw = Button(main_window, text="Firewall", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: firewall_window())
btnfw.pack(pady=20)
btnmon = Button(main_window, text="AIDE", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: monitor_window())
btnmon.pack(pady=20)
main_window.mainloop()
def process_window():
global process_window
process_window = Toplevel(main_window)
process_window.title("Process Configuration")
process_window.geometry("800x600")
process_window.configure(bg="dark grey")
label1 = Label(process_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def firewall_window():
firewall_window = Toplevel(main_window)
firewall_window.title("Firewall Configuration")
firewall_window.geometry("1000x600")
firewall_window.configure(bg="dark grey")
label1 = Label(firewall_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
updatebtn = Button(firewall_window, text="View Current Iptables layout", font=('arial', 9, 'bold'), bg="light grey",
fg="black", width="30",
height="2", command=lambda: updateipt())
updatebtn.pack(pady=20)
def monitor_window():
monitor_window = Toplevel(main_window)
monitor_window.title("AIDE Configuration")
monitor_window.geometry("800x600")
monitor_window.configure(bg="dark grey")
label1 = Label(monitor_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def updateipt():
text = Text(firewall_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line,)
main_window()

In your code, the name of your functions are also the name of your windows (Toplevel). Please change all your function names. Also, in your updateipt function, you are giving a function to place the Text widget so it throws an error.
import os
import subprocess as sub
from tkinter import *
from subprocess import Popen, PIPE
def main_windows():
global main_window
main_window = Tk()
main_window.title("Firewall test")
main_window.geometry("1000x700")
main_window.configure(bg="dark grey")
label1 = Label(main_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
btnproc = Button(main_window, text="Process configuration", font=('arial', 9, 'bold'), bg="light grey", fg="black",
width="30", height="2", command=lambda: process_windows())
btnproc.pack(pady=20)
btnfw = Button(main_window, text="Firewall", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: firewall_windows())
btnfw.pack(pady=20)
btnmon = Button(main_window, text="AIDE", font=('arial', 9, 'bold'), bg="light grey", fg="black", width="30",
height="2", command=lambda: monitor_windows())
btnmon.pack(pady=20)
main_window.mainloop()
def process_windows():
global process_window
process_window = Toplevel()
process_window.title("Process Configuration")
process_window.geometry("800x600")
process_window.configure(bg="dark grey")
label1 = Label(process_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def firewall_windows():
firewall_window = Toplevel()
firewall_window.title("Firewall Configuration")
firewall_window.geometry("1000x600")
firewall_window.configure(bg="dark grey")
label1 = Label(firewall_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
updatebtn = Button(firewall_window, text="View Current Iptables layout", font=('arial', 9, 'bold'), bg="light grey",
fg="black", width="30",
height="2", command=lambda: updateipt())
updatebtn.pack(pady=20)
def monitor_windows():
monitor_window = Toplevel(main_window)
monitor_window.title("AIDE Configuration")
monitor_window.geometry("800x600")
monitor_window.configure(bg="dark grey")
label1 = Label(monitor_window, text="What Would you like to configure?", font=('arial', 12, 'bold'), bg="white",
fg="black")
label1.pack(fill=X, pady=20)
def updateipt():
text = Text(main_window, height=150, width=124)
text.pack()
with Popen(["iptables", '-L', '-v', '-n'], stdout=PIPE, stderr=PIPE) as p:
for line in p.stdout:
text.insert(END, line)
main_windows()

Related

How to remove 2 buttons by pressing one?

I want to remove the buttons "play" and "help" by pressing just on button "play". How can I do that? I need that the button "play" destroy himself and in addition destroy the button "help"
This is my code:
from tkinter import *
import tkinter.messagebox
from random import *
window = Tk()
window.title("Simon")
window.geometry("300x200")
label = Label(window, text="Simon Game!", font=("Ariel", 80),
bg="CadetBlue3")
label.pack()
window.configure(bg="CadetBlue3")
def destroy(button):
def inner():
button.destroy()
return inner
def click_help_button():
tkinter.messagebox.showinfo("Instructions", "The device
creates a series of tones and lights and requires a user to
repeat the sequence. If the user succeeds, the series becomes
progressively longer and more complex. Once the user fails, the
game is over")
help_btn = Button(window, width=12, height=2, text="Help",
bg="grey",font=("Ariel", 18), command=click_help_button)
help_btn.pack(side='bottom')
help_btn.place(x=800, y=150)
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=destroy(help_btn))
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
start_btn.config(command=destroy(start_btn))
red_btn = Button(window, width=35, height=15, bg='red')
red_btn.place(x=495, y=270)
green_btn = Button(window, width=35, height=15, bg='green')
green_btn.place(x=750, y=270)
blue_btn = Button(window, width=35, height=15, bg='blue')
blue_btn.place(x=495, y=495)
yellow_btn = Button(window, width=35, height=15, bg='yellow')
yellow_btn.place(x=750, y=495)
window.mainloop()
Thanks to those who help!
I would make a click_play_button function
def click_play_button():
start_btn.destroy()
help_btn.destroy()
And call on it when pressing the play button
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=click_play_button)
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
Below also worked...
def destroy(button):
button.destroy()
def click_help_button():
tkinter.messagebox.showinfo("Instructions", "The device")
help_btn = Button(window, width=12, height=2, text="Help",
bg="grey", font=("Ariel", 18), command=click_help_button)
help_btn.pack(side='bottom')
help_btn.place(x=800, y=150)
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=lambda: [destroy(help_btn), destroy(start_btn)])
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
red_btn = Button(window, width=35, height=15, bg='red')
red_btn.place(x=495, y=270)
green_btn = Button(window, width=35, height=15, bg='green')
green_btn.place(x=750, y=270)
blue_btn = Button(window, width=35, height=15, bg='blue')
blue_btn.place(x=495, y=495)
yellow_btn = Button(window, width=35, height=15, bg='yellow')
yellow_btn.place(x=750, y=495)
window.mainloop()

TKINTER QUIZ GAME

I am a beginner in programming and in Python. I am trying to build a quiz game with tkinter in which I call a csv file that has 6 columns, (QUESTION, ANSWERA, ANSWERB, ANSWERC, ANSWERD, CORRECTANSWER) in a python file. I have an entry box(for the questions) and 4 buttons(for the answers).
My question: How do I interate through the list created for the csv file through the command in the buttons?
When I click on the button, with the right or wrong answer, I want it to change the text at the buttons and take the values from the next row in the list.
My code:
from tkinter import*
import pygame
import sys
pygame.init()
root = Tk()
root.title("ΜΑΘΕ ΠΑΙΖΟΝΤΑΣ")
root.geometry('1352x652+0+0')
root.configure(background = 'blue')
#=================CONNECT TO DATABASE csv=========================
import csv
import unicodedata
with open('questiondb.csv',newline='',encoding="utf8")as csvfile:
csvreader=csv.reader(csvfile,delimiter=',',quotechar='|')
rows=list(csvreader)
for i in range(1,3):
print(rows[i])
#=================functions=============
def correct_answer_funcA():
if answerA==correctanswer:
print ("right!!!")
else:
print("wrong!!")
def correct_answer_funcB():
if answerB==correctanswer:
print ("right!!!")
else:
print("wrong!!")
def correct_answer_funcC():
if answerC==correctanswer:
print ("right!!!")
else:
print("wrong!!")
def correct_answer_funcD():
if answerD==correctanswer:
print ("right!!!")
else:
print("wrong!!")
#===============TEXT,LABELS,BUTTON=======================
i=1
questions=rows[i][1]
answerA=rows[i][2]
answerB=rows[i][3]
answerC=rows[i][4]
answerD=rows[i][5]
correctanswer=rows[i][6]
txtQuestion = Entry(ABC1c, font=('arial', 18,'bold'),bg='red', fg='white', bd=1, width=44,justify=CENTER)
txtQuestion.grid(row=0, column=0, columnspan=4, pady=4)
txtQuestion.insert(INSERT,questions)
lblQuestA = Label(ABC1c, font=('arial', 14,'bold'),text="A: ",bg='black', fg='white', bd=1, justify=CENTER)
lblQuestA.grid(row=1, column=0, pady=4, sticky=W)
txtQuestion1 = Button(ABC1c, font=('arial', 14,'bold'),bg='blue', fg='white', bd=1, width=17, height=2,justify=CENTER, text=answerA, command=correct_answer_funcA)
txtQuestion1.grid(row=1, column=1, pady=4)
lblQuestB = Label(ABC1c, font=('arial', 14,'bold'),text="B: ",bg='black', fg='white', bd=1,justify=LEFT)
lblQuestB.grid(row=1, column=2, pady=4, sticky=W)
txtQuestion2 = Button(ABC1c, font=('arial', 14,'bold'),bg='blue', fg='white', bd=1, width=17, height=2,justify=CENTER, text = answerB, command=correct_answer_funcB)
txtQuestion2.grid(row=1, column=3, pady=4)
lblQuestC = Label(ABC1c, font=('arial', 14,'bold'),text="C: ",bg='black', fg='white', bd=1, justify=CENTER)
lblQuestC.grid(row=2, column=0, pady=4, sticky=W)
txtQuestion3 = Button(ABC1c, font=('arial', 14,'bold'),bg='blue', fg='white', bd=1, width=17, height=2,justify=CENTER, text = answerC, command=correct_answer_funcC)
txtQuestion3.grid(row=2, column=1, pady=4)
lblQuestD = Label(ABC1c, font=('arial', 14,'bold'),text="B: ",bg='black', fg='white', bd=1,justify=LEFT)
lblQuestD.grid(row=2, column=2, pady=4, sticky=W)
txtQuestion4 = Button(ABC1c, font=('arial', 14,'bold'),bg='blue', fg='white', bd=1, width=17, height=2,justify=CENTER, text = answerD, command=correct_answer_funcD)
txtQuestion4.grid(row=2, column=3, pady=4)

Increasing Size of Tab Button in Tkinter Notebook

How can you increase the size of the button used to access the tab?
I've tried adding padding, changing the font size, and editing height/width, but none of these affect the physical size of the button used to switch tabs.
Change the style like:
customed_style = ttk.Style()
customed_style.configure('Custom.TNotebook.Tab', padding=[12, 12], font=('Helvetica', 10))
Then use this style to your tab like:
tab_control = ttk.Notebook(self.master, style='Custom.TNotebook')
Here is a full example:
import tkinter as tk
from tkinter import ttk
class MainWindow:
def __init__(self, master):
self.master = master
self.master.title("Large Tab Example")
self.createTabs()
def createTabs(self):
self.tab_control = ttk.Notebook(self.master, style='Custom.TNotebook')
self.tab_one = ttk.Frame(self.tab_control)
self.tab_control.add(self.tab_one, text="Tab One")
self.frame_one = ttk.Frame(self.tab_one)
self.frame_one.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.label_one = ttk.Label(self.frame_one, text="Tab One", font=('Helvetica', 24, 'bold'))
self.label_one.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.tab_two = ttk.Frame(self.tab_control)
self.tab_control.add(self.tab_two, text="Tab Two")
self.frame_two = ttk.Frame(self.tab_two)
self.frame_two.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.label_two = ttk.Label(self.frame_two, text="Tab Two", font=('Helvetica', 24, 'bold'))
self.label_two.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.tab_three = ttk.Frame(self.tab_control)
self.tab_control.add(self.tab_three, text="Tab Three")
self.frame_three = ttk.Frame(self.tab_three)
self.frame_three.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.label_three = ttk.Label(self.frame_three, text="Tab Three", font=('Helvetica', 24, 'bold'))
self.label_three.grid(row=0, column=0, padx=16, pady=16, sticky='nesw')
self.tab_control.grid(row=0, column=0, sticky='nesw', padx=4, pady=4)
def main():
root = tk.Tk()
customed_style = ttk.Style()
customed_style.configure('Custom.TNotebook.Tab', padding=[12, 12], font=('Helvetica', 10))
customed_style.configure('Custom.TNotebook', tabposition='wn')
app = MainWindow(root)
root.mainloop()
if __name__ == '__main__':
main()

display of minus and plus in tkinter calculator

Now I'm making calculator with python and tkinter, but i had one little problem. Minus and plus displaing in a really strange way and I don't think that it's looks cool.Look at Entry in which calculation should happend
So, I just want to know how can i centered them (move minus a little more higher).
My code:
from tkinter import *
root = Tk()
root.title("Calculator")
root.resizable(width=False, height=False)
# Main variables
equation = StringVar()
equation.set("0")
equa=""
# Program functions
def ButtonPress(num):
global equa
equa = equa + str(num)
equation.set(equa)
# Widgets
calculation = Entry(root, textvariable=equation, font=("Arial", 15,"bold"),
bd=12, insertwidth=4, width=15)
calculation.grid(columnspan=4)
# Numbers
button1 = Button(root, text='1', command=lambda: ButtonPress(1), bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button1.grid(row=1, column=0, sticky=W)
button2 = Button(root, text='2', command=lambda:ButtonPress(2),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button2.grid(row=1, column=1, sticky=W)
button3 = Button(root, text='3', command=lambda: ButtonPress(3),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button3.grid(row=1, column=2, sticky=W)
button4 = Button(root, text='4', command=lambda: ButtonPress(4),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button4.grid(row=2, column=0, sticky=W)
button5 = Button(root, text='5', command=lambda: ButtonPress(5),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button5.grid(row=2, column=1, sticky=W)
button6 = Button(root, text='6', command=lambda: ButtonPress(6),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button6.grid(row=2, column=2, sticky=W)
button7 = Button(root, text='7', command=lambda: ButtonPress(7),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button7.grid(row=3, column=0, sticky=W)
button8 = Button(root, text='8', command=lambda: ButtonPress(8),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button8.grid(row=3, column=1, sticky=W)
button9 = Button(root, text='9', command=lambda: ButtonPress(9),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button9.grid(row=3, column=2, sticky=W)
button0 = Button(root, text='0', command=lambda: ButtonPress(0),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button0.grid(row=4, column=1, sticky=W)
button_plus = Button(root, text='+', command=lambda: ButtonPress('+'),bg="gainsboro",bd=3, padx=12, pady=5, font=("Arial", 13, "bold"))
button_plus.grid(row=1, column=3, sticky=W)
button_minus = Button(root, text='-', command=lambda: ButtonPress('-'),bg="gainsboro",bd=3, padx=14, pady=5, font=("Arial", 13, "bold"))
button_minus.grid(row=2, column=3, sticky=W)
root.mainloop()
The simplest solution is to choose a monospaced font, e.g. you could try:
calculation = Entry(root, textvariable=equation, font=("Courier", 15,"bold"),
bd=12, insertwidth=4, width=15)
calculation.grid(columnspan=4)

Python Tkinter Entry() Calculations

I am currently trying to build a GUI calculator using python with the help of tkinter. I have managed to set up all of my buttons and they interact with my entry() bar when I press the button (e,g: Press button 5 and 5 appears into the entry()).
The only thing left to do is actually perform the mathematical equations that appear in the entry(). For example, if I enter 5 + 5 * 2 into the entry bar, how would I make the answer appear into the entry() after it's updated? So basically all I'm asking is someone to help me make this happen!
I have provided the code below and a screenshot of the calculator. Also please don't report this as a duplicate or flag this question as a post, (I'm reasking this question because I got no help on my last one so please help a young python programmer out!). Also I'm asking you not to provide me with links because I've read every possible link on tkinter there is to read and still have no clue what I'm doing.
Here is my code:
import sys
from tkinter import *
from PIL import Image, ImageTk
#ACTIONS:
def clear():
#Action: Clears the entry().
txtDisplay.delete(0,END);
return;
def update_Entry(inputValue):
#Updates the entry when a button is pressed.
currentText = num1.get();
update = num1.set(currentText + inputValue);
#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');
#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33, insertwidth = 1, font = 40, justify=RIGHT);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();
print(txtDisplay.get())
#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('0'));
zeroButton.place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('1'));
oneButton.place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('2'));
twoButton.place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('3'));
threeButton.place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('4'));
fourButton.place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('5'));
fiveButton.place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('6'));
sixButton.place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('7'));
sevenButton.place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('8'));
eightButton.place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('9'));
ninthButton.place(x=182, y=142);
decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue', command=lambda:update_Entry('.'));
decimalButton.place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen', command=lambda:update_Entry('='));
equalButton.place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command=lambda:update_Entry('+'));
plusButton.place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray', command=lambda:update_Entry('-'));
minusButton.place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray', command=lambda:update_Entry('*'));
multiplyButton.place(x=264, y=66);
divideButton = Button(root, text='÷', width=8, height=3, bg='gray', command=lambda:update_Entry('/'));
divideButton.place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command = clear, bg='Orange');
clearButton.place(x=17, y=66);
#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);
#Parent window's background color:
root.configure(background = 'black');
root.mainloop();
Screenshot:
For something this simple, try having this as the command for your equalButton:
def evaluate():
currentText = num1.get()
try:
num1.set(str(eval(currentText)))
except SyntaxError:
num1.set('<ERROR>')

Categories