2017-07-15 42 views
1

我是Python的新手,顯然在使用checkbutton時丟失了一些重要的東西。這是我的程序背後的想法:我手動選擇一個文件,然後根據複選框是否被選中,使用按鈕觸發一個計算序列或另一個計算序列。爲了達到這個目的,我想使用.get()命令來驗證複選框的狀態。同時使用一個checkbutton和一個按鈕

我發現的是,只有一個序列始終獨立於複選框的狀態而被觸發。 .get()沒有更新,當我點擊複選框。我究竟做錯了什麼?任何幫助將不勝感激。

from tkinter import * 
from tkinter import filedialog 
import tkinter as tk 

master = Tk() 
root = tk.Tk() 

col_sep = "\t" 

col_h_b = [] # field column for background 
col_m_b = [] # magnetization column for background 

def choose_b_file(): 
    root.fileName_b = filedialog.askopenfilename(filetypes=((".dat files", "*.dat"), ("All files", "*.*"))) 
    with open(root.fileName_b, 'r') as f: 
     for line in f: 
      if line[0] != "#": 
       linedata = [float(line.split(col_sep)[i]) for i in range(len(line.split(col_sep)))] 
       col_h_b.append(linedata[4]) 
       col_m_b.append(linedata[5]) 
    print(f.name) 

offset = BooleanVar() 
checkbox = tk.Checkbutton(root, text="offset subtraction", variable=offset,onvalue=1, offvalue=0) 
checkbox.pack() 

def plot(): 
    if offset.get() == 1: 
     #some mathematical operations and graph plotting 
    else: 
     #other mathematical operations and graph plotting 

def close_window(): 
    exit() 

b_data = Button(master, text="Background", width=20, command=choose_b_file) 
m_minus_b = Button(master, text="Plot", width=5, command=plot) 
quit = Button(master, text="Quit", width=5, command=close_window) 

b_data.pack() 
m_minus_b.pack() 
quit.pack() 

root.mainloop() 

回答

1

你多半搞亂父母部件rootmaster。 您需要爲複選框設置單獨的窗口嗎?

否則,速戰速決是master中的複選框創建更換root

checkbox = tk.Checkbutton(root, text="offset subtraction" ...) 

您還可以簡化布爾的東西,對於checkbutton的默認行爲是使用0和1,並取出主或根,只選一個。

from tkinter import * 
from tkinter import filedialog 

root = Tk() 

col_sep = "\t"  
col_h_b = [] # field column for background 
col_m_b = [] # magnetization column for background 

def choose_b_file(): 
    root.fileName_b = filedialog.askopenfilename(filetypes=((".dat files", "*.dat"), ("All files", "*.*"))) 
    with open(root.fileName_b, 'r') as f: 
     for line in f: 
      if line[0] != "#": 
       linedata = [float(line.split(col_sep)[i]) for i in range(len(line.split(col_sep)))] 
       col_h_b.append(linedata[4]) 
       col_m_b.append(linedata[5]) 
    print(f.name) 

def plot(): 
    if offset.get() == 1: 
     print('True') 
     #some mathematical operations and graph plotting 
    else: 
     print('False') 
     #other mathematical operations and graph plotting 

def close_window(): 
    exit() 

offset = IntVar() 
checkbox = Checkbutton(root, text="offset subtraction", variable=offset) 
checkbox.pack() 

b_data = Button(root, text="Background", width=20, command=choose_b_file) 
m_minus_b = Button(root, text="Plot", width=5, command=plot) 
quit = Button(root, text="Quit", width=5, command=close_window) 

b_data.pack() 
m_minus_b.pack() 
quit.pack() 

root.mainloop() 
+0

非常感謝@PrMoureu!這就是訣竅!事實上,我還試圖弄清楚如何在同一窗口中顯示覆選框和按鈕。所以你在一篇文章中解決了這兩個問題:-) – DenGor

相關問題